From c115dc27ab2e21e121874555b630ba77348badcf Mon Sep 17 00:00:00 2001 From: r266-tech Date: Tue, 10 Nov 2026 19:37:32 +0800 Subject: [PATCH 01/85] fix(usage): read Fable weekly quotas from scoped limits --- .../repository/claude_usage_service_test.go | 85 +++++++++++++++++++ .../internal/service/account_usage_service.go | 35 +++++++- .../account_usage_service_fable_test.go | 57 +++++++++++++ 3 files changed, 175 insertions(+), 2 deletions(-) diff --git a/backend/internal/repository/claude_usage_service_test.go b/backend/internal/repository/claude_usage_service_test.go index cbd0b6d3ea..f8235c379e 100644 --- a/backend/internal/repository/claude_usage_service_test.go +++ b/backend/internal/repository/claude_usage_service_test.go @@ -2,11 +2,15 @@ package repository import ( "context" + "fmt" "io" "net/http" "net/http/httptest" "testing" + "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -61,6 +65,87 @@ func (s *ClaudeUsageServiceSuite) TestFetchUsage_Success() { require.Equal(s.T(), "oauth-2025-04-20", captured.anthropicBeta, "anthropic-beta header mismatch") } +type claudeUsageWindowAccountRepo struct { + service.AccountRepository + account *service.Account +} + +func (r *claudeUsageWindowAccountRepo) GetByID(context.Context, int64) (*service.Account, error) { + return r.account, nil +} + +func (r *claudeUsageWindowAccountRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error { + for key, value := range updates { + r.account.Extra[key] = value + } + return nil +} + +type claudeUsageWindowLogRepo struct { + service.UsageLogRepository +} + +func (*claudeUsageWindowLogRepo) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) { + return &usagestats.AccountStats{}, nil +} + +func TestClaudeUsageFetcher_ScopedFableRoundTrip(t *testing.T) { + resetAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Microsecond) + for _, tc := range []struct { + name string + percent string + legacy string + wantUsage float64 + }{ + {name: "scoped", percent: "5.25", wantUsage: 5.25}, + {name: "zero overrides passive", percent: "0", wantUsage: 0}, + {name: "missing falls back to passive", percent: "null", wantUsage: 87}, + {name: "legacy takes precedence", percent: "5.25", legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantUsage: 56}, + } { + t.Run(tc.name, func(t *testing.T) { + legacy := tc.legacy + if legacy == "" { + legacy = "null" + } + requests := make(chan [2]string, 2) + srv := newLocalTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests <- [2]string{r.Method, r.URL.Path} + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"five_hour":{"utilization":12},"seven_day_overage_included":%s,"limits":[{"kind":"weekly_scoped","group":"weekly","percent":%s,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}]}`, legacy, tc.percent, resetAt.Format(time.RFC3339Nano)) + })) + defer srv.Close() + fetcher := &claudeUsageService{usageURL: srv.URL + "/api/oauth/usage", allowPrivateHosts: true} + account := &service.Account{ + ID: 1, Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Credentials: map[string]any{"access_token": "test-token"}, + Extra: map[string]any{ + "passive_usage_7d_oi_utilization": 0.87, + "passive_usage_7d_oi_reset": resetAt.Unix(), + }, + } + repo := &claudeUsageWindowAccountRepo{account: account} + svc := service.NewAccountUsageService(repo, &claudeUsageWindowLogRepo{}, fetcher, + nil, nil, nil, nil, nil, service.NewUsageCache(), nil, nil) + for range 2 { + usage, err := svc.GetUsageForAccount(t.Context(), account) + require.NoError(t, err) + require.NotNil(t, usage.SevenDayFable) + require.Equal(t, tc.wantUsage, usage.SevenDayFable.Utilization) + require.NotNil(t, usage.SevenDayFable.ResetsAt) + require.Equal(t, resetAt.Unix(), usage.SevenDayFable.ResetsAt.Unix()) + } + passive, err := svc.GetPassiveUsage(t.Context(), account.ID) + require.NoError(t, err) + require.NotNil(t, passive.SevenDayFable) + require.InDelta(t, tc.wantUsage, passive.SevenDayFable.Utilization, 1e-9) + require.Equal(t, resetAt.Unix(), passive.SevenDayFable.ResetsAt.Unix()) + require.InDelta(t, tc.wantUsage/100, account.Extra["passive_usage_7d_oi_utilization"], 1e-9) + require.Len(t, requests, 1, "the second query must reuse the decoded API response") + require.Equal(t, [2]string{"GET", "/api/oauth/usage"}, <-requests) + }) + } +} + func (s *ClaudeUsageServiceSuite) TestFetchUsage_NonOK() { s.srv = newLocalTestServer(s.T(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index f9a8904e6c..9fb4b74a86 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -287,8 +287,20 @@ type ClaudeUsageResponse struct { } `json:"seven_day_sonnet"` // Fable 专属 7d 窗口(对应响应头 7d_oi,claim 名为 seven_day_overage_included, // 见 anthropic-ratelimit-unified-representative-claim 头)。上游 usage API - // 若不下发该字段,GetUsage 会用被动采样数据回填。 + // 若不下发该字段,先读取 limits[],仍缺失时 GetUsage 用被动采样回填。 SevenDayOverageIncluded ClaudeUsageWindow `json:"seven_day_overage_included"` + Limits []struct { + Kind string `json:"kind"` + Group string `json:"group"` + Percent *float64 `json:"percent"` + ResetsAt string `json:"resets_at"` + Scope struct { + Model struct { + DisplayName string `json:"display_name"` + } `json:"model"` + Surface json.RawMessage `json:"surface"` + } `json:"scope"` + } `json:"limits"` } // ClaudeUsageFetchOptions 包含获取 Claude 用量数据所需的所有选项 @@ -1773,7 +1785,26 @@ func (s *AccountUsageService) buildUsageInfo(resp *ClaudeUsageResponse, updatedA } // 7天Fable窗口(响应头 7d_oi 对应的窗口) - if fable := resp.SevenDayOverageIncluded; fable.ResetsAt != "" { + fable := resp.SevenDayOverageIncluded + if fable.ResetsAt == "" { + // 新版 usage 将模型周窗口放在 limits[]。仅投影无 surface 限定的 + // Fable 周额度;percent 已是百分比,显式 0 也必须覆盖旧被动采样。 + for _, limit := range resp.Limits { + if limit.Kind != "weekly_scoped" || limit.Group != "weekly" || + limit.Scope.Model.DisplayName != "Fable" || limit.Percent == nil || *limit.Percent < 0 { + continue + } + if surface := bytes.TrimSpace(limit.Scope.Surface); len(surface) > 0 && !bytes.Equal(surface, []byte("null")) { + continue + } + if _, err := parseTime(limit.ResetsAt); err != nil { + continue + } + fable = ClaudeUsageWindow{Utilization: *limit.Percent, ResetsAt: limit.ResetsAt} + break + } + } + if fable.ResetsAt != "" { if fableReset, err := parseTime(fable.ResetsAt); err == nil { info.SevenDayFable = &UsageProgress{ Utilization: fable.Utilization, diff --git a/backend/internal/service/account_usage_service_fable_test.go b/backend/internal/service/account_usage_service_fable_test.go index 60f2e9c79f..072979198b 100644 --- a/backend/internal/service/account_usage_service_fable_test.go +++ b/backend/internal/service/account_usage_service_fable_test.go @@ -2,6 +2,8 @@ package service import ( "encoding/json" + "fmt" + "strings" "testing" "time" @@ -56,6 +58,61 @@ func TestBuildUsageInfo_SevenDayFable(t *testing.T) { require.Nil(t, info.SevenDayFable) } +func TestBuildUsageInfo_ScopedFableLimits(t *testing.T) { + resetAt := time.Now().Add(72 * time.Hour).In(time.FixedZone("UTC+8", 8*60*60)).Truncate(time.Microsecond) + entry := fmt.Sprintf(`{"kind":"weekly_scoped","group":"weekly","percent":5.25,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}`, resetAt.Format(time.RFC3339Nano)) + for _, tc := range []struct { + name string + limits string + legacy string + wantWindow bool + wantUsage float64 + }{ + {name: "inactive scoped window", limits: entry, wantWindow: true, wantUsage: 5.25}, + {name: "active scoped window", limits: strings.Replace(entry, `"is_active":false`, `"is_active":true`, 1), wantWindow: true, wantUsage: 5.25}, + {name: "omitted surface", limits: strings.Replace(entry, `,"surface":null`, ``, 1), wantWindow: true, wantUsage: 5.25}, + {name: "zero percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":0`, 1), wantWindow: true}, + {name: "over quota percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":105.25`, 1), wantWindow: true, wantUsage: 105.25}, + {name: "legacy takes precedence", limits: entry, legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantWindow: true, wantUsage: 56}, + {name: "null legacy", limits: entry, legacy: "null", wantWindow: true, wantUsage: 5.25}, + {name: "other model", limits: strings.Replace(entry, `"Fable"`, `"Sonnet"`, 1)}, + {name: "unscoped weekly", limits: strings.Replace(entry, `"weekly_scoped"`, `"weekly"`, 1)}, + {name: "other group", limits: strings.Replace(entry, `"group":"weekly"`, `"group":"daily"`, 1)}, + {name: "missing model", limits: strings.Replace(entry, `{"display_name":"Fable"}`, `null`, 1)}, + {name: "surface restricted", limits: strings.Replace(entry, `"surface":null`, `"surface":{"display_name":"Claude Code"}`, 1)}, + {name: "missing percent", limits: strings.Replace(entry, `"percent":5.25,`, ``, 1)}, + {name: "null percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":null`, 1)}, + {name: "negative percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":-1`, 1)}, + {name: "missing reset", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "", 1)}, + {name: "invalid reset", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "not-a-time", 1)}, + {name: "invalid entry before valid", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "not-a-time", 1) + "," + entry, wantWindow: true, wantUsage: 5.25}, + {name: "unknown entry before valid", limits: `null,{"kind":"future_limit"},` + entry, wantWindow: true, wantUsage: 5.25}, + } { + t.Run(tc.name, func(t *testing.T) { + legacy := tc.legacy + if legacy == "" { + legacy = "null" + } + raw := fmt.Sprintf(`{"five_hour":{"utilization":12},"seven_day":{"utilization":34,"resets_at":%q},"seven_day_overage_included":%s,"limits":[%s]}`, resetAt.Format(time.RFC3339Nano), legacy, tc.limits) + var resp ClaudeUsageResponse + require.NoError(t, json.Unmarshal([]byte(raw), &resp)) + now := time.Now() + info := (&AccountUsageService{}).buildUsageInfo(&resp, &now) + require.Equal(t, 12.0, info.FiveHour.Utilization) + require.Equal(t, 34.0, info.SevenDay.Utilization) + if !tc.wantWindow { + require.Nil(t, info.SevenDayFable) + return + } + require.NotNil(t, info.SevenDayFable) + require.Equal(t, tc.wantUsage, info.SevenDayFable.Utilization) + require.NotNil(t, info.SevenDayFable.ResetsAt) + require.True(t, resetAt.Equal(*info.SevenDayFable.ResetsAt)) + require.Positive(t, info.SevenDayFable.RemainingSeconds) + }) + } +} + func TestBuildPassiveUsageWindow(t *testing.T) { future := time.Now().Add(48 * time.Hour).Unix() From 43511b40e977060ba173b68dbb6fd1e89d2fe578 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:56:34 +0800 Subject: [PATCH 02/85] fix(payment): make Alipay refund request id stable across retries Alipay refunds used a UnixNano timestamp as out_request_no, so an admin retry after an ambiguous gateway error minted a new request and refunded the user twice. Use the same deterministic order+amount id as the other providers (wxpayRefundID, Stripe idempotency key). Same order and amount now map to the same Alipay refund request; the existing QueryRefund prefix contract is unchanged. --- backend/internal/payment/provider/alipay.go | 14 ++++- .../internal/payment/provider/alipay_test.go | 61 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/backend/internal/payment/provider/alipay.go b/backend/internal/payment/provider/alipay.go index dbd0e9cccb..555913b086 100644 --- a/backend/internal/payment/provider/alipay.go +++ b/backend/internal/payment/provider/alipay.go @@ -348,7 +348,7 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen return nil, err } - outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano()) + outRequestNo := fmt.Sprintf("%s%s%s", req.OrderID, alipayRefundRequestSep, alipayRefundRequestNoSuffix(req.Amount)) result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{ OutTradeNo: req.OrderID, RefundAmount: req.Amount, @@ -374,6 +374,18 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen }, nil } +// alipayRefundRequestNoSuffix 生成跨重试稳定的 out_request_no 后缀。 +// 支付宝把相同的 out_request_no 视为同一次退款请求;如果重试换号, +// "网关已受理但返回错误"后的重试会变成第二笔真实退款。 +// 与 wxpayRefundID 一致,用金额区分同一订单的不同退款金额。 +func alipayRefundRequestNoSuffix(amount string) string { + normalized := strings.NewReplacer(".", "", "-", "").Replace(strings.TrimSpace(amount)) + if normalized == "" { + return "0" + } + return normalized +} + // QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS // 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。 func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) { diff --git a/backend/internal/payment/provider/alipay_test.go b/backend/internal/payment/provider/alipay_test.go index a2264b2eef..4e5751b9ad 100644 --- a/backend/internal/payment/provider/alipay_test.go +++ b/backend/internal/payment/provider/alipay_test.go @@ -480,6 +480,67 @@ func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) { } } +// out_request_no 必须跨重试稳定:支付宝把相同的 out_request_no 视为同一次退款请求。 +// 如果重试生成新的请求号,一次"网关已受理但返回错误"的重试会退两次。 +func TestAlipayRefundOutRequestNoIsStableAcrossRetries(t *testing.T) { + origRefund := alipayTradeRefund + t.Cleanup(func() { alipayTradeRefund = origRefund }) + + var outRequestNos []string + alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) { + outRequestNos = append(outRequestNos, param.OutRequestNo) + return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil + } + + provider := &Alipay{client: &alipay.Client{}} + req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"} + for i := 0; i < 2; i++ { + if _, err := provider.Refund(context.Background(), req); err != nil { + t.Fatalf("Refund() error = %v", err) + } + } + + if len(outRequestNos) != 2 { + t.Fatalf("got %d refund calls, want 2", len(outRequestNos)) + } + if outRequestNos[0] != "sub2_7-refund-1250" { + t.Fatalf("out_request_no = %q, want sub2_7-refund-1250", outRequestNos[0]) + } + if outRequestNos[0] != outRequestNos[1] { + t.Fatalf("out_request_no changed across retries: %q != %q", outRequestNos[0], outRequestNos[1]) + } +} + +// 模拟支付宝的幂等语义:相同的 out_request_no 只产生一笔真实退款。 +// 重试时如果请求号变了,钱会被退两次;稳定请求号下只退一次。 +func TestAlipayRefundRetryDoesNotDoubleRefund(t *testing.T) { + origRefund := alipayTradeRefund + t.Cleanup(func() { alipayTradeRefund = origRefund }) + + const refundCents = 1250 + refundedCents := 0 + seen := make(map[string]struct{}) + alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) { + if _, ok := seen[param.OutRequestNo]; !ok { + seen[param.OutRequestNo] = struct{}{} + refundedCents += refundCents + } + return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil + } + + provider := &Alipay{client: &alipay.Client{}} + req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"} + for i := 0; i < 2; i++ { + if _, err := provider.Refund(context.Background(), req); err != nil { + t.Fatalf("Refund() error = %v", err) + } + } + + if refundedCents != refundCents { + t.Fatalf("retry refunded %d cents, want %d (one refund only)", refundedCents, refundCents) + } +} + func TestAlipayQueryRefundMapsStatus(t *testing.T) { origQuery := alipayTradeFastPayRefundQuery t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery }) From 37a0f3870b5a269b2957987d86bc76022710bca1 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:55:51 +0800 Subject: [PATCH 03/85] fix(billing): scope RPM override to the group it belongs to The auth cache snapshot records the (user, group) RPM override for the API key's group. checkRPM used it for any group whenever it was non-nil, so a fallback request (for example the Antigravity prompt-too-long path) applied group A's override to group B: override=0 disabled B's rpm_limit entirely, while a positive override throttled B to the wrong rate. Only trust the snapshot override when UserGroupRPMOverrideGroupID matches the current group; otherwise fall back to the DB lookup as the snapshot versioning intended. --- .../internal/service/billing_cache_service.go | 2 +- .../service/rpm_override_group_repro_test.go | 58 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/rpm_override_group_repro_test.go diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go index 39435f90bd..f899130de9 100644 --- a/backend/internal/service/billing_cache_service.go +++ b/backend/internal/service/billing_cache_service.go @@ -940,7 +940,7 @@ func (s *BillingCacheService) checkRPM(ctx context.Context, user *User, group *G if group != nil { // 解析 override:优先从 auth cache snapshot;snapshot 未确认该分组时回退 DB。 var override *int - if user.UserGroupRPMOverride != nil || user.UserGroupRPMOverrideGroupID == group.ID { + if user.UserGroupRPMOverrideGroupID == group.ID { override = user.UserGroupRPMOverride } else if s.userGroupRateRepo != nil { dbOverride, err := s.userGroupRateRepo.GetRPMOverrideByUserAndGroup(ctx, user.ID, group.ID) diff --git a/backend/internal/service/rpm_override_group_repro_test.go b/backend/internal/service/rpm_override_group_repro_test.go new file mode 100644 index 0000000000..42e805250a --- /dev/null +++ b/backend/internal/service/rpm_override_group_repro_test.go @@ -0,0 +1,58 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +// 复现:snapshot 里的 override 属于分组 10,但请求跑到分组 11 时, +// 当前实现仍然使用分组 10 的 override,导致分组 11 的 rpm_limit 失效。 +func TestBillingCacheService_CheckRPM_OverrideFromAnotherGroupMustNotApply(t *testing.T) { + zero := 0 // 分组 10 的 override:0 = 免检 + cache := &userRPMCacheStub{ + userGroupCounts: []int{1, 2, 3, 4, 5, 6}, // 分组 11 的 RPM 计数 + } + repo := &rpmOverrideRepoStub{} // 分组 11 没有 override + svc := newBillingServiceForRPM(t, cache, repo) + + user := &User{ + ID: 1, + UserGroupRPMOverride: &zero, + UserGroupRPMOverrideGroupID: 10, + } + group := &Group{ID: 11, RPMLimit: 5} + + for i := 0; i < 5; i++ { + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + } + require.ErrorIs(t, svc.checkRPM(context.Background(), user, group), ErrGroupRPMExceeded, + "分组 11 的 rpm_limit 应生效,不能使用分组 10 的 override") + require.EqualValues(t, 6, atomic.LoadInt32(&repo.calls), + "snapshot 只确认了分组 10,分组 11 应回源查询") +} + +// override 属于当前分组时必须直接生效,且不应回源查询(保留 snapshot 缓存优化)。 +func TestBillingCacheService_CheckRPM_SnapshotOverrideAppliesForItsOwnGroup(t *testing.T) { + override := 2 + cache := &userRPMCacheStub{userGroupCounts: []int{1, 2, 3}} + repo := &rpmOverrideRepoStub{err: errors.New("must not be queried")} + svc := newBillingServiceForRPM(t, cache, repo) + + user := &User{ + ID: 1, + UserGroupRPMOverride: &override, + UserGroupRPMOverrideGroupID: 10, + } + group := &Group{ID: 10, RPMLimit: 100} + + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + require.ErrorIs(t, svc.checkRPM(context.Background(), user, group), ErrGroupRPMExceeded) + require.Zero(t, atomic.LoadInt32(&repo.calls), "分组 10 的 override 已确认,不应回源") +} From 1546c0c18e97225cc657444ea8406d1088ebd740 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:57:56 +0800 Subject: [PATCH 04/85] perf(gateway): skip JSON decode for forwarded Anthropic stream events Anthropic SSE processing decoded every data line into map[string]any even though most events (content_block_delta, ping, ...) are forwarded verbatim. A 120-byte text delta cost ~915ns, 1185B and 20 allocations; a 1500-chunk response burned ~1.4ms CPU and ~30k allocations for no semantic gain. Parse only events that can change usage, model, cache_control or keepalive state. Replace the per-line SSE regex with a prefix check, and add a string variant of tool-name restoration so the streaming writer no longer copies each chunk through []byte/string. Benchmark (content_block_delta): 915ns/20 allocs/1185B -> 164ns/0 allocs/0B. Output remains byte-for-byte identical; existing streaming tests pass. --- .../service/gateway_anthropic_passthrough.go | 2 +- .../gateway_forward_as_chat_completions.go | 2 +- .../service/gateway_forward_as_responses.go | 2 +- backend/internal/service/gateway_service.go | 3 - .../service/gateway_streaming_test.go | 101 ++++++++++++++++++ .../internal/service/gateway_tool_rewrite.go | 35 +++++- .../service/gateway_tool_rewrite_test.go | 40 +++++++ .../service/gateway_upstream_response.go | 60 ++++++++++- ...teway_chat_completions_anthropic_native.go | 2 +- ...penai_gateway_messages_anthropic_native.go | 2 +- 10 files changed, 234 insertions(+), 15 deletions(-) diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index e7c99cb076..a1f7922822 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -561,7 +561,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } if !clientDisconnected { - restored := string(reverseToolNamesIfPresent(c, []byte(line))) + restored := reverseToolNamesIfPresentString(c, line) if _, err := io.WriteString(w, restored); err != nil { clientDisconnected = true logger.LegacyPrintf("service.gateway", "[Anthropic passthrough] Client disconnected during streaming, continue draining upstream for usage: account=%d", account.ID) diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index f2e3f0027e..0177558a3e 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -434,7 +434,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( } // Reverse tool name mapping: fake → real, per-chunk bytes.Replace. // c 可能持有请求侧注入的 ToolNameRewrite;无则仅做静态前缀还原。 - out := string(reverseToolNamesIfPresent(c, []byte(sse))) + out := reverseToolNamesIfPresentString(c, sse) if _, err := fmt.Fprint(c.Writer, out); err != nil { return true // client disconnected } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 802d090457..761cd5b904 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -665,7 +665,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( if err != nil { continue } - out := string(reverseToolNamesIfPresent(c, []byte(sse))) + out := reverseToolNamesIfPresentString(c, sse) fmt.Fprint(c.Writer, out) //nolint:errcheck } c.Writer.Flush() diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..9186ddffbb 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -402,10 +402,7 @@ func isClaudeCodeCredentialScopeError(msg string) bool { strings.Contains(m, "cannot be used for other api requests") } -// sseDataRe matches SSE data lines with optional whitespace after colon. -// Some upstream APIs return non-standard "data:" without space (should be "data: "). var ( - sseDataRe = regexp.MustCompile(`^data:\s*`) claudeCliUserAgentRe = regexp.MustCompile(`(?i)^claude-cli/\d+\.\d+\.\d+`) // claudeCodePromptPrefixes 用于检测 Claude Code 系统提示词的前缀列表 diff --git a/backend/internal/service/gateway_streaming_test.go b/backend/internal/service/gateway_streaming_test.go index cf0adfaa24..e5a2ccab47 100644 --- a/backend/internal/service/gateway_streaming_test.go +++ b/backend/internal/service/gateway_streaming_test.go @@ -532,3 +532,104 @@ func TestHandleStreamingResponse_SSEErrorEvent_NonJSONDataLine(t *testing.T) { }) require.Equal(t, "", ExtractUpstreamErrorMessage([]byte(sseErr.RawData))) } + +func TestSSEEventNeedsJSONParse(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + eventName string + data string + keepalive bool + modelReplace bool + want bool + }{ + { + name: "content_block_delta is forwarded verbatim", + eventName: "content_block_delta", + data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}`, + want: false, + }, + { + name: "ping is forwarded verbatim", + eventName: "ping", + data: `{"type":"ping"}`, + want: false, + }, + { + name: "message_start needs usage parsing", + eventName: "message_start", + data: `{"type":"message_start","message":{"usage":{"input_tokens":1}}}`, + want: true, + }, + { + name: "message_delta needs usage parsing", + eventName: "message_delta", + data: `{"type":"message_delta","usage":{"output_tokens":1}}`, + want: true, + }, + { + name: "missing event name falls back to parsing", + eventName: "", + data: `{"type":"content_block_delta"}`, + want: true, + }, + { + name: "keepalive needs block fields", + eventName: "content_block_delta", + data: `{"type":"content_block_delta","index":0}`, + keepalive: true, + want: true, + }, + { + name: "model replace needs message parsing", + eventName: "content_block_start", + data: `{"type":"content_block_start","message":{"model":"x"}}`, + modelReplace: true, + want: true, + }, + { + name: "unknown event with usage must be parsed", + eventName: "custom_event", + data: `{"usage":{"input_tokens":1}}`, + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, sseEventNeedsJSONParse(tt.eventName, []byte(tt.data), tt.keepalive, tt.modelReplace)) + }) + } +} + +// 快路径必须原样转发 content_block_delta,不能重新序列化改变 key 顺序/空格/转义; +// message_stop 在没有 keepalive 的情况下也要能被识别为终态。 +func TestHandleStreamingResponse_FastPathForwardsDeltaBytesVerbatim(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newMinimalGatewayService() + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + + pr, pw := io.Pipe() + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + + delta := `{"delta":{"text":"你好","type":"text_delta"},"type":"content_block_delta","index":0,"extra":"a b"}` + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("event: content_block_delta\ndata: " + delta + "\n\n")) + _, _ = pw.Write([]byte("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")) + }() + + result, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + _ = pr.Close() + require.NoError(t, err) + require.NotNil(t, result) + + body := rec.Body.String() + require.Contains(t, body, "event: content_block_delta\ndata: "+delta+"\n\n", + "网关必须逐字节转发不需要改写的 delta") + require.Contains(t, body, "event: message_stop") +} diff --git a/backend/internal/service/gateway_tool_rewrite.go b/backend/internal/service/gateway_tool_rewrite.go index c3e1d8da7f..31991fd9db 100644 --- a/backend/internal/service/gateway_tool_rewrite.go +++ b/backend/internal/service/gateway_tool_rewrite.go @@ -351,10 +351,14 @@ func restoreToolNamesInBytes(data []byte, rw *ToolNameRewrite) []byte { // replaceAllBytes 是 bytes.ReplaceAll 的便捷封装,避免每个调用点各自做 []byte 转换。 func replaceAllBytes(data []byte, from, to string) []byte { - if len(data) == 0 || from == to || !strings.Contains(string(data), from) { + if len(data) == 0 || from == to { return data } - return []byte(strings.ReplaceAll(string(data), from, to)) + fromBytes := []byte(from) + if !bytes.Contains(data, fromBytes) { + return data + } + return bytes.ReplaceAll(data, fromBytes, []byte(to)) } // toolNameRewriteFromContext 从 gin.Context 取出请求阶段保存的工具名映射。 @@ -384,3 +388,30 @@ func reverseToolNamesIfPresent(c interface { } return restoreToolNamesInBytes(chunk, rw) } + +// reverseToolNamesIfPresentString is the string-typed variant for streaming +// writers. The common case (no tool names in the chunk) returns the original +// string without any []byte/string copy. +func reverseToolNamesIfPresentString(c interface { + Get(string) (any, bool) +}, chunk string) string { + rw := toolNameRewriteFromContext(c) + if rw == nil && len(staticToolNameRewrites) == 0 { + return chunk + } + if rw != nil { + for _, pair := range rw.ReverseOrdered { + fake, real := pair[0], pair[1] + if fake == "" || fake == real || !strings.Contains(chunk, fake) { + continue + } + chunk = strings.ReplaceAll(chunk, fake, real) + } + } + for prefix, replacement := range staticToolNameRewrites { + if strings.Contains(chunk, replacement) { + chunk = strings.ReplaceAll(chunk, replacement, prefix) + } + } + return chunk +} diff --git a/backend/internal/service/gateway_tool_rewrite_test.go b/backend/internal/service/gateway_tool_rewrite_test.go index 04f405b129..d34fd0e546 100644 --- a/backend/internal/service/gateway_tool_rewrite_test.go +++ b/backend/internal/service/gateway_tool_rewrite_test.go @@ -358,3 +358,43 @@ func BenchmarkApplyToolNameRewriteToBody_LongHistory(b *testing.B) { _ = applyToolNameRewriteToBody(body, rw) } } + +type toolRewriteCtxStub struct { + rw *ToolNameRewrite +} + +func (c toolRewriteCtxStub) Get(key string) (any, bool) { + if key == toolNameRewriteKey && c.rw != nil { + return c.rw, true + } + return nil, false +} + +// 字符串版本和 bytes 版本的还原结果必须完全一致,流式路径才能安全替换。 +func TestReverseToolNamesStringMatchesBytes(t *testing.T) { + rw := &ToolNameRewrite{ + ReverseOrdered: [][2]string{ + {"sessions_abc", "session_abc"}, + {"sessions_x", "sessions_x"}, + }, + } + cases := []string{ + "plain chunk", + `{"name":"sessions_x"}`, + `{"name":"sessions_abc"}`, + `{"name":"sessions_abc","x":"session_y"}`, + `{"name":"sessions_x","y":"sessions_abc","z":"session_y"}`, + } + for _, in := range cases { + got := reverseToolNamesIfPresentString(toolRewriteCtxStub{rw: rw}, in) + want := string(reverseToolNamesIfPresent(toolRewriteCtxStub{rw: rw}, []byte(in))) + require.Equal(t, want, got, "input=%q", in) + } + + // mapping 为 nil 时仍要做静态前缀还原。 + for _, in := range []string{`sessions_a`, `session_b`, `plain`} { + got := reverseToolNamesIfPresentString(toolRewriteCtxStub{}, in) + want := string(reverseToolNamesIfPresent(toolRewriteCtxStub{}, []byte(in))) + require.Equal(t, want, got, "input=%q", in) + } +} diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 85b415e5cf..86900cbe37 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -706,6 +706,36 @@ func partialStreamUsageResult(c *gin.Context, resp *http.Response, streamResult } } +// SSE fast-path predicates. Package-level byte slices keep the per-event +// checks allocation-free. +var ( + sseUsageFieldBytes = []byte(`"usage"`) + sseMessageFieldBytes = []byte(`"message"`) + sseModelFieldBytes = []byte(`"model"`) + sseMessageStopValueBytes = []byte(`"message_stop"`) +) + +// sseEventNeedsJSONParse reports whether an Anthropic SSE data line must be +// decoded into map[string]any. Most stream events (content_block_delta, ping, +// etc.) are forwarded verbatim; decoding them only adds allocations and GC +// pressure on the hot path. +func sseEventNeedsJSONParse(eventName string, data []byte, useNoopDeltaKeepalive, needModelReplace bool) bool { + eventName = strings.ToLower(strings.TrimSpace(eventName)) + if eventName == "" || eventName == "message_start" || eventName == "message_delta" { + return true + } + if useNoopDeltaKeepalive { + switch eventName { + case "content_block_start", "content_block_delta", "content_block_stop", "message_stop": + return true + } + } + if needModelReplace && bytes.Contains(data, sseMessageFieldBytes) { + return true + } + return bytes.Contains(data, sseUsageFieldBytes) +} + func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, startTime time.Time, originalModel, mappedModel string, mimicClaudeCode bool) (*streamingResult, error) { observer := upstreamResponseModelObserverFromContext(c) if observer == nil { @@ -877,8 +907,8 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http eventName = strings.TrimSpace(strings.TrimPrefix(trimmed, "event:")) continue } - if dataLine == "" && sseDataRe.MatchString(trimmed) { - dataLine = sseDataRe.ReplaceAllString(trimmed, "") + if dataLine == "" && strings.HasPrefix(trimmed, "data:") { + dataLine = strings.TrimLeft(strings.TrimPrefix(trimmed, "data:"), " \t\n\f\r") } } @@ -900,8 +930,28 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http return []string{block}, dataLine, nil, nil } + dataLineBytes := []byte(dataLine) + if !sseEventNeedsJSONParse(eventName, dataLineBytes, useNoopDeltaKeepalive, needModelReplace) { + // Fast path: the event is forwarded verbatim. Skip the map decode and + // only do the cheap observations that still need the raw payload. + if bytes.Contains(dataLineBytes, sseModelFieldBytes) { + observer.ObserveAnthropic(dataLineBytes) + } + if strings.EqualFold(eventName, "message_stop") || bytes.Contains(dataLineBytes, sseMessageStopValueBytes) { + if anthropicStreamEventIsTerminal(eventName, dataLine) { + sawTerminalEvent = true + } + } + block := "" + if eventName != "" { + block = "event: " + eventName + "\n" + } + block += "data: " + dataLine + "\n\n" + return []string{block}, dataLine, nil, nil + } + var event map[string]any - if err := json.Unmarshal([]byte(dataLine), &event); err != nil { + if err := json.Unmarshal(dataLineBytes, &event); err != nil { // JSON 解析失败,直接透传原始数据 block := "" if eventName != "" { @@ -1101,8 +1151,8 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http for _, block := range outputBlocks { if !clientDisconnected { - restored := reverseToolNamesIfPresent(c, []byte(block)) - if _, werr := fmt.Fprint(w, string(restored)); werr != nil { + restored := reverseToolNamesIfPresentString(c, block) + if _, werr := io.WriteString(w, restored); werr != nil { clientDisconnected = true logger.LegacyPrintf("service.gateway", "Client disconnected during streaming, continuing to drain upstream for billing") // 不 break:客户端断开后仍需继续合并本事件及后续事件的 usage, diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 5c2d86b87d..8c6b68b223 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -410,7 +410,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( if err != nil { return false } - out := string(reverseToolNamesIfPresent(c, []byte(sse))) + out := reverseToolNamesIfPresentString(c, sse) if _, err := fmt.Fprint(c.Writer, out); err != nil { clientDisconnected = true return false diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 3156aa8546..a2978fc5ca 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -483,7 +483,7 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( } if !clientDisconnected { - restored := string(reverseToolNamesIfPresent(c, []byte(line))) + restored := reverseToolNamesIfPresentString(c, line) if _, err := io.WriteString(w, restored); err != nil { clientDisconnected = true logger.LegacyPrintf("service.gateway", "[CN Anthropic 直通] Client disconnected during streaming, continue draining upstream for usage: account=%d", account.ID) From 98a44ba3f36f3acfd77cebc796fc10248c582018 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:34:54 +0800 Subject: [PATCH 05/85] fix(billing): make group rate/RPM sync transactional SyncGroupRateMultipliers and SyncGroupRPMOverrides ran three destructive statements in autocommit mode: clear rows missing from the payload, delete all-NULL rows, then upsert the payload. If the upsert failed (deleted user FK, duplicate user_id, transient DB error), the clear and delete had already committed, silently wiping the group's overrides. Wrap each sync in one transaction and dedupe entries by user_id before writing so ON CONFLICT cannot hit the same row twice. Any failure now rolls the whole sync back. Add sqlmock tests covering commit, rollback and dedupe. --- .../repository/user_group_rate_repo.go | 119 +++++++++++---- .../user_group_rate_repo_sync_test.go | 138 ++++++++++++++++++ 2 files changed, 228 insertions(+), 29 deletions(-) create mode 100644 backend/internal/repository/user_group_rate_repo_sync_test.go diff --git a/backend/internal/repository/user_group_rate_repo.go b/backend/internal/repository/user_group_rate_repo.go index 74d25cb0b6..81b17654e0 100644 --- a/backend/internal/repository/user_group_rate_repo.go +++ b/backend/internal/repository/user_group_rate_repo.go @@ -3,6 +3,7 @@ package repository import ( "context" "database/sql" + "fmt" "time" "github.com/Wei-Shaw/sub2api/internal/service" @@ -11,11 +12,55 @@ import ( type userGroupRateRepository struct { sql sqlExecutor + db *sql.DB } // NewUserGroupRateRepository 创建用户专属分组倍率/RPM 仓储 func NewUserGroupRateRepository(sqlDB *sql.DB) service.UserGroupRateRepository { - return &userGroupRateRepository{sql: sqlDB} + return &userGroupRateRepository{sql: sqlDB, db: sqlDB} +} + +func (r *userGroupRateRepository) beginTx(ctx context.Context) (*sql.Tx, error) { + if r == nil || r.db == nil { + return nil, fmt.Errorf("user group rate repository: database handle is not configured") + } + return r.db.BeginTx(ctx, nil) +} + +// dedupeGroupRateMultiplierEntries 按 user_id 去重,保留最后一次出现的值。 +// ON CONFLICT DO UPDATE 对同一行出现两次会直接报错,去重后才能安全写入。 +func dedupeGroupRateMultiplierEntries(entries []service.GroupRateMultiplierInput) []service.GroupRateMultiplierInput { + if len(entries) < 2 { + return entries + } + index := make(map[int64]int, len(entries)) + out := make([]service.GroupRateMultiplierInput, 0, len(entries)) + for _, entry := range entries { + if pos, ok := index[entry.UserID]; ok { + out[pos] = entry + continue + } + index[entry.UserID] = len(out) + out = append(out, entry) + } + return out +} + +func dedupeGroupRPMOverrideEntries(entries []service.GroupRPMOverrideInput) []service.GroupRPMOverrideInput { + if len(entries) < 2 { + return entries + } + index := make(map[int64]int, len(entries)) + out := make([]service.GroupRPMOverrideInput, 0, len(entries)) + for _, entry := range entries { + if pos, ok := index[entry.UserID]; ok { + out[pos] = entry + continue + } + index[entry.UserID] = len(out) + out = append(out, entry) + } + return out } // GetByUserID 获取用户所有专属分组 rate_multiplier(仅返回非 NULL 的条目) @@ -244,14 +289,22 @@ func (r *userGroupRateRepository) SyncUserGroupRates(ctx context.Context, userID // - 未出现在 entries 中的用户行:rate_multiplier 归 NULL;若 rpm_override 也为 NULL 则整行删除。 // - 出现的用户行:upsert rate_multiplier。 func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, groupID int64, entries []service.GroupRateMultiplierInput) error { + entries = dedupeGroupRateMultiplierEntries(entries) + keepUserIDs := make([]int64, 0, len(entries)) for _, e := range entries { keepUserIDs = append(keepUserIDs, e.UserID) } + tx, err := r.beginTx(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + // 未在 entries 列表中的行:清空 rate_multiplier。 if len(keepUserIDs) == 0 { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rate_multiplier = NULL, updated_at = NOW() WHERE group_id = $1 @@ -259,7 +312,7 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, return err } } else { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rate_multiplier = NULL, updated_at = NOW() WHERE group_id = $1 AND user_id <> ALL($2) @@ -269,32 +322,33 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, } // 清空后若整行 NULL 则删除。 - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` DELETE FROM user_group_rate_multipliers WHERE group_id = $1 AND rate_multiplier IS NULL AND rpm_override IS NULL `, groupID); err != nil { return err } - if len(entries) == 0 { - return nil + if len(entries) > 0 { + userIDs := make([]int64, len(entries)) + rates := make([]float64, len(entries)) + for i, e := range entries { + userIDs[i] = e.UserID + rates[i] = e.RateMultiplier + } + now := time.Now() + if _, err := tx.ExecContext(ctx, ` + INSERT INTO user_group_rate_multipliers (user_id, group_id, rate_multiplier, created_at, updated_at) + SELECT data.user_id, $1::bigint, data.rate_multiplier, $2::timestamptz, $2::timestamptz + FROM unnest($3::bigint[], $4::double precision[]) AS data(user_id, rate_multiplier) + ON CONFLICT (user_id, group_id) + DO UPDATE SET rate_multiplier = EXCLUDED.rate_multiplier, updated_at = EXCLUDED.updated_at + `, groupID, now, pq.Array(userIDs), pq.Array(rates)); err != nil { + return err + } } - userIDs := make([]int64, len(entries)) - rates := make([]float64, len(entries)) - for i, e := range entries { - userIDs[i] = e.UserID - rates[i] = e.RateMultiplier - } - now := time.Now() - _, err := r.sql.ExecContext(ctx, ` - INSERT INTO user_group_rate_multipliers (user_id, group_id, rate_multiplier, created_at, updated_at) - SELECT data.user_id, $1::bigint, data.rate_multiplier, $2::timestamptz, $2::timestamptz - FROM unnest($3::bigint[], $4::double precision[]) AS data(user_id, rate_multiplier) - ON CONFLICT (user_id, group_id) - DO UPDATE SET rate_multiplier = EXCLUDED.rate_multiplier, updated_at = EXCLUDED.updated_at - `, groupID, now, pq.Array(userIDs), pq.Array(rates)) - return err + return tx.Commit() } // SyncGroupRPMOverrides 同步分组的 rpm_override 部分(不触动 rate_multiplier)。 @@ -302,6 +356,8 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, // - 未出现的用户行:rpm_override 归 NULL;若 rate_multiplier 也为 NULL 则整行删除。 // - 出现的用户行:若 RPMOverride 为 nil 则清空;非 nil 则 upsert。 func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, groupID int64, entries []service.GroupRPMOverrideInput) error { + entries = dedupeGroupRPMOverrideEntries(entries) + keepUserIDs := make([]int64, 0, len(entries)) var clearUserIDs []int64 upsertUserIDs := make([]int64, 0, len(entries)) @@ -316,9 +372,15 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro } } + tx, err := r.beginTx(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + // 未在 entries 列表中的行:清空 rpm_override。 if len(keepUserIDs) == 0 { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rpm_override = NULL, updated_at = NOW() WHERE group_id = $1 @@ -326,7 +388,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro return err } } else { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rpm_override = NULL, updated_at = NOW() WHERE group_id = $1 AND user_id <> ALL($2) @@ -337,7 +399,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro // 显式 clear 的行。 if len(clearUserIDs) > 0 { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rpm_override = NULL, updated_at = NOW() WHERE group_id = $1 AND user_id = ANY($2) @@ -347,7 +409,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro } // 清空后若整行 NULL 则删除。 - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` DELETE FROM user_group_rate_multipliers WHERE group_id = $1 AND rate_multiplier IS NULL AND rpm_override IS NULL `, groupID); err != nil { @@ -356,19 +418,18 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro if len(upsertUserIDs) > 0 { now := time.Now() - _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` INSERT INTO user_group_rate_multipliers (user_id, group_id, rpm_override, created_at, updated_at) SELECT data.user_id, $1::bigint, data.rpm_override, $2::timestamptz, $2::timestamptz FROM unnest($3::bigint[], $4::integer[]) AS data(user_id, rpm_override) ON CONFLICT (user_id, group_id) DO UPDATE SET rpm_override = EXCLUDED.rpm_override, updated_at = EXCLUDED.updated_at - `, groupID, now, pq.Array(upsertUserIDs), pq.Array(upsertValues)) - if err != nil { + `, groupID, now, pq.Array(upsertUserIDs), pq.Array(upsertValues)); err != nil { return err } } - return nil + return tx.Commit() } // ClearGroupRPMOverrides 清空指定分组所有行的 rpm_override。 diff --git a/backend/internal/repository/user_group_rate_repo_sync_test.go b/backend/internal/repository/user_group_rate_repo_sync_test.go new file mode 100644 index 0000000000..cd6d6282d4 --- /dev/null +++ b/backend/internal/repository/user_group_rate_repo_sync_test.go @@ -0,0 +1,138 @@ +package repository + +import ( + "context" + "errors" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSyncGroupRateMultipliersCommitsInOneTransaction(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + err = repo.SyncGroupRateMultipliers(context.Background(), 10, []service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 1.5}, + }) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSyncGroupRateMultipliersRollsBackOnInsertFailure(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 2)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnError(errors.New("insert failed")) + mock.ExpectRollback() + + err = repo.SyncGroupRateMultipliers(context.Background(), 10, []service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 1.5}, + }) + require.ErrorContains(t, err, "insert failed") + require.NoError(t, mock.ExpectationsWereMet(), "the destructive UPDATE/DELETE must be rolled back") +} + +func TestSyncGroupRPMOverridesCommitsInOneTransaction(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + override := 5 + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + err = repo.SyncGroupRPMOverrides(context.Background(), 10, []service.GroupRPMOverrideInput{ + {UserID: 1, RPMOverride: &override}, + }) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSyncGroupRPMOverridesRollsBackOnInsertFailure(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + override := 5 + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 2)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnError(errors.New("insert failed")) + mock.ExpectRollback() + + err = repo.SyncGroupRPMOverrides(context.Background(), 10, []service.GroupRPMOverrideInput{ + {UserID: 1, RPMOverride: &override}, + }) + require.ErrorContains(t, err, "insert failed") + require.NoError(t, mock.ExpectationsWereMet(), "the destructive UPDATE/DELETE must be rolled back") +} + +func TestDedupeGroupRateMultiplierEntriesKeepsLastValue(t *testing.T) { + got := dedupeGroupRateMultiplierEntries([]service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 1}, + {UserID: 2, RateMultiplier: 2}, + {UserID: 1, RateMultiplier: 3}, + }) + require.Equal(t, []service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 3}, + {UserID: 2, RateMultiplier: 2}, + }, got) +} + +func TestDedupeGroupRPMOverrideEntriesKeepsLastValue(t *testing.T) { + five := 5 + got := dedupeGroupRPMOverrideEntries([]service.GroupRPMOverrideInput{ + {UserID: 1}, + {UserID: 2, RPMOverride: &five}, + {UserID: 1, RPMOverride: &five}, + }) + require.Len(t, got, 2) + require.Equal(t, int64(1), got[0].UserID) + require.Equal(t, &five, got[0].RPMOverride) + require.Equal(t, int64(2), got[1].UserID) +} From 5846bfbbfaccb3bfad8f3bc006e2619306aaadb4 Mon Sep 17 00:00:00 2001 From: feeeei Date: Wed, 11 Nov 2026 10:12:47 +0800 Subject: [PATCH 06/85] =?UTF-8?q?fix(gemini):=20=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=20chat=20=E8=AF=B7=E6=B1=82=E8=BD=AC?= =?UTF-8?q?=E5=8F=91=20response=5Fformat=20=E7=BB=93=E6=9E=84=E5=8C=96?= =?UTF-8?q?=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /v1/chat/completions 走 Gemini 账号时,response_format 在 chat→Responses→Anthropic 转换中丢失,上游只能靠 prompt 约束 JSON 格式。现在按客户端原始 response_format 写 generationConfig:json_object 写 responseMimeType=application/json;json_schema 另把 json_schema.schema 原样写入 responseJsonSchema。请求带 tools 或上游模型为图片输出 模型时不写。 Code Assist(OAuth + project_id)包装改为原字节嵌入 request,避免 Unmarshal→Marshal 重排 schema 属性顺序、截断大整数。 --- .../gemini_chat_completions_compat_service.go | 21 ++- .../service/gemini_compat_response_format.go | 50 ++++++ .../gemini_compat_response_format_test.go | 168 ++++++++++++++++++ 3 files changed, 233 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/gemini_compat_response_format.go create mode 100644 backend/internal/service/gemini_compat_response_format_test.go diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index f0716e003c..8b74b3311a 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -16,6 +16,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" + "github.com/tidwall/sjson" ) // ForwardAsChatCompletions serves OpenAI Chat Completions clients through @@ -66,7 +67,7 @@ func (s *GeminiMessagesCompatService) ForwardAsChatCompletions( return nil, fmt.Errorf("marshal chat completions compat request: %w", err) } - return s.forwardClaudeBodyAsChatCompletions(ctx, c, account, claudeBody, originalModel, clientStream, includeUsage, startTime) + return s.forwardClaudeBodyAsChatCompletions(ctx, c, account, claudeBody, ccReq.ResponseFormat, originalModel, clientStream, includeUsage, startTime) } func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( @@ -74,6 +75,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( c *gin.Context, account *Account, claudeBody []byte, + responseFormat json.RawMessage, originalModel string, clientStream bool, includeUsage bool, @@ -104,6 +106,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( } geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq) geminiReq = applyGeminiCompatThinkingConfig(geminiReq, claudeBody, mappedModel, clientStream) + geminiReq = applyGeminiChatResponseFormat(geminiReq, responseFormat, mappedModel) proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { @@ -383,15 +386,21 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF fullURL += "?alt=sse" } - var inner any - if err := json.Unmarshal(geminiReq, &inner); err != nil { - return nil, "", fmt.Errorf("failed to parse gemini request: %w", err) + // request 按原字节嵌入,保留 responseJsonSchema 等 schema 的属性顺序与数值字面量。 + if !json.Valid(geminiReq) { + return nil, "", errors.New("failed to parse gemini request: invalid JSON") } - wrappedBytes, _ := json.Marshal(map[string]any{ + wrapperBytes, err := json.Marshal(map[string]any{ "model": mappedModel, "project": projectID, - "request": inner, }) + if err != nil { + return nil, "", err + } + wrappedBytes, err := sjson.SetRawBytes(wrapperBytes, "request", geminiReq) + if err != nil { + return nil, "", err + } upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(wrappedBytes)) if err != nil { diff --git a/backend/internal/service/gemini_compat_response_format.go b/backend/internal/service/gemini_compat_response_format.go new file mode 100644 index 0000000000..457067d878 --- /dev/null +++ b/backend/internal/service/gemini_compat_response_format.go @@ -0,0 +1,50 @@ +package service + +import ( + "encoding/json" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// applyGeminiChatResponseFormat 把 Chat Completions 的 response_format 写入 Gemini generationConfig: +// json_object 写 responseMimeType=application/json;json_schema 另把 json_schema.schema 原样写入 +// responseJsonSchema(JSON Schema 形态,不转换为 OpenAPI 子集的 responseSchema)。 +// text、缺省或无法解析的 response_format 不改请求。 +// 以下情况不写:请求带 tools(Gemini 2.x 不接受工具与 JSON responseMimeType 同用); +// upstreamModel 为图片输出模型(输出含图片,与 JSON responseMimeType 冲突)。 +func applyGeminiChatResponseFormat(geminiReq []byte, responseFormat json.RawMessage, upstreamModel string) []byte { + if len(responseFormat) == 0 || !gjson.ValidBytes(responseFormat) || isGeminiImageOutputModel(upstreamModel) { + return geminiReq + } + format := gjson.ParseBytes(responseFormat) + if !format.IsObject() { + return geminiReq + } + + var schema gjson.Result + switch format.Get("type").String() { + case "json_object": + case "json_schema": + schema = format.Get("json_schema.schema") + default: + return geminiReq + } + + if tools := gjson.GetBytes(geminiReq, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + return geminiReq + } + + out, err := sjson.SetBytes(geminiReq, "generationConfig.responseMimeType", "application/json") + if err != nil { + return geminiReq + } + if schema.IsObject() { + withSchema, err := sjson.SetRawBytes(out, "generationConfig.responseJsonSchema", []byte(schema.Raw)) + if err != nil { + return geminiReq + } + out = withSchema + } + return out +} diff --git a/backend/internal/service/gemini_compat_response_format_test.go b/backend/internal/service/gemini_compat_response_format_test.go new file mode 100644 index 0000000000..9d554a3fb9 --- /dev/null +++ b/backend/internal/service/gemini_compat_response_format_test.go @@ -0,0 +1,168 @@ +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strconv" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const geminiResponseFormatTestSchema = `{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"score":{"type":"integer","minimum":1,"maximum":10},"note":{"anyOf":[{"type":"string","maxLength":600},{"type":"null"}]}},"required":["score","note"],"additionalProperties":false}` + +func TestApplyGeminiChatResponseFormat(t *testing.T) { + base := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"maxOutputTokens":32000,"thinkingConfig":{"thinkingLevel":"high"}}}`) + withTools := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tools":[{"functionDeclarations":[{"name":"lookup"}]}],"generationConfig":{"maxOutputTokens":100}}`) + noConfig := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`) + + tests := []struct { + name string + req []byte + format string + model string + wantMime bool + wantSchema string + }{ + {name: "json_schema writes mime and schema", req: base, format: `{"type":"json_schema","json_schema":{"name":"grade","strict":true,"schema":` + geminiResponseFormatTestSchema + `}}`, wantMime: true, wantSchema: geminiResponseFormatTestSchema}, + {name: "json_schema without schema writes mime only", req: base, format: `{"type":"json_schema","json_schema":{"name":"grade"}}`, wantMime: true}, + {name: "json_object writes mime only", req: base, format: `{"type":"json_object"}`, wantMime: true}, + {name: "json_object creates generationConfig", req: noConfig, format: `{"type":"json_object"}`, wantMime: true}, + {name: "text leaves request unchanged", req: base, format: `{"type":"text"}`}, + {name: "null leaves request unchanged", req: base, format: `null`}, + {name: "empty leaves request unchanged", req: base, format: ``}, + {name: "invalid json leaves request unchanged", req: base, format: `{"type":"json_object"`}, + {name: "non-object leaves request unchanged", req: base, format: `"json_object"`}, + {name: "image model leaves request unchanged", req: base, format: `{"type":"json_object"}`, model: "gemini-2.5-flash-image"}, + {name: "unlisted image model leaves request unchanged", req: base, format: `{"type":"json_object"}`, model: "models/gemini-3.5-flash-image-preview"}, + {name: "text model writes mime", req: base, format: `{"type":"json_object"}`, model: "gemini-4-argon", wantMime: true}, + {name: "tools present leaves request unchanged", req: withTools, format: `{"type":"json_schema","json_schema":{"name":"grade","schema":` + geminiResponseFormatTestSchema + `}}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := applyGeminiChatResponseFormat(tt.req, json.RawMessage(tt.format), tt.model) + require.True(t, json.Valid(got), string(got)) + if !tt.wantMime { + require.Equal(t, string(tt.req), string(got)) + return + } + require.Equal(t, "application/json", gjson.GetBytes(got, "generationConfig.responseMimeType").String()) + schema := gjson.GetBytes(got, "generationConfig.responseJsonSchema") + if tt.wantSchema == "" { + require.False(t, schema.Exists(), string(got)) + } else { + require.JSONEq(t, tt.wantSchema, schema.Raw) + } + require.False(t, gjson.GetBytes(got, "generationConfig.responseSchema").Exists(), string(got)) + require.Equal(t, gjson.GetBytes(tt.req, "contents").Raw, gjson.GetBytes(got, "contents").Raw) + for _, path := range []string{"generationConfig.maxOutputTokens", "generationConfig.thinkingConfig"} { + require.Equal(t, gjson.GetBytes(tt.req, path).Raw, gjson.GetBytes(got, path).Raw, path) + } + }) + } +} + +func TestGeminiForwardAsChatCompletions_ForwardsResponseFormat(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + stream bool + format string + wantSchema string + }{ + {name: "non-stream json_schema", format: `{"type":"json_schema","json_schema":{"name":"grade","strict":true,"schema":` + geminiResponseFormatTestSchema + `}}`, wantSchema: geminiResponseFormatTestSchema}, + {name: "stream json_object", stream: true, format: `{"type":"json_object"}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resp := &http.Response{StatusCode: http.StatusOK} + if tt.stream { + resp.Header = http.Header{"Content-Type": []string{"text/event-stream"}} + resp.Body = io.NopCloser(strings.NewReader(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"{\"score\":7,\"note\":null}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5}}` + "\n\n")) + } else { + resp.Header = http.Header{"Content-Type": []string{"application/json"}} + resp.Body = io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"{\"score\":7,\"note\":null}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5}}`)) + } + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{resp}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-4-argon","stream":` + strconv.FormatBool(tt.stream) + `,"reasoning_effort":"high","max_tokens":32000,"response_format":` + tt.format + `,"messages":[{"role":"user","content":"grade this"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := upstream.requestBodies[0] + require.Equal(t, "application/json", gjson.GetBytes(sent, "generationConfig.responseMimeType").String(), string(sent)) + schema := gjson.GetBytes(sent, "generationConfig.responseJsonSchema") + if tt.wantSchema == "" { + require.False(t, schema.Exists(), string(sent)) + } else { + require.JSONEq(t, tt.wantSchema, schema.Raw) + } + require.Equal(t, "high", gjson.GetBytes(sent, "generationConfig.thinkingConfig.thinkingLevel").String()) + require.Equal(t, int64(32000), gjson.GetBytes(sent, "generationConfig.maxOutputTokens").Int()) + if !tt.stream { + require.Equal(t, `{"score":7,"note":null}`, gjson.Get(recorder.Body.String(), "choices.0.message.content").String()) + } + }) + } +} + +func TestGeminiForwardAsChatCompletions_ResponseFormatSkippedWithTools(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`)), + }}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-4-argon","response_format":{"type":"json_object"},"tools":[{"type":"function","function":{"name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}}],"messages":[{"role":"user","content":"hi"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := upstream.requestBodies[0] + require.True(t, gjson.GetBytes(sent, "tools").IsArray(), string(sent)) + require.False(t, gjson.GetBytes(sent, "generationConfig.responseMimeType").Exists(), string(sent)) + require.False(t, gjson.GetBytes(sent, "generationConfig.responseJsonSchema").Exists(), string(sent)) +} + +func TestGeminiForwardAsChatCompletions_CodeAssistKeepsResponseSchemaBytes(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(`data: {"response":{"candidates":[{"content":{"parts":[{"text":"{\"reasoning\":\"r\",\"answer\":\"a\"}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5}}}` + "\n\n")), + }}} + svc := &GeminiMessagesCompatService{tokenProvider: &GeminiTokenProvider{}, httpUpstream: upstream, cfg: &config.Config{}} + account := &Account{ + ID: 612, + Platform: PlatformGemini, + Type: AccountTypeOAuth, + Credentials: map[string]any{"access_token": "ya29.test-token", "project_id": "project-1"}, + Concurrency: 1, + } + schema := `{"type":"object","properties":{"reasoning":{"type":"string"},"answer":{"type":"string"},"big":{"type":"integer","maximum":9007199254740993}},"required":["reasoning","answer"]}` + body := []byte(`{"model":"gemini-4-argon","response_format":{"type":"json_schema","json_schema":{"name":"r","schema":` + schema + `}},"messages":[{"role":"user","content":"hi"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := upstream.requestBodies[0] + require.Equal(t, "gemini-4-argon", gjson.GetBytes(sent, "model").String()) + require.Equal(t, "project-1", gjson.GetBytes(sent, "project").String()) + require.Equal(t, "application/json", gjson.GetBytes(sent, "request.generationConfig.responseMimeType").String(), string(sent)) + require.Equal(t, schema, gjson.GetBytes(sent, "request.generationConfig.responseJsonSchema").Raw) + require.Equal(t, `{"reasoning":"r","answer":"a"}`, gjson.Get(recorder.Body.String(), "choices.0.message.content").String()) +} From 74ba91aa6b6d130d0b0029fabffed6ce3425dffe Mon Sep 17 00:00:00 2001 From: jaxxjj Date: Tue, 10 Nov 2026 19:09:30 -0800 Subject: [PATCH 07/85] fix(openai): keep Codex forks on their parent's prompt cache key An ephemeral Codex fork, such as app-server thread/sample, keeps its parent's session-id header and prompt_cache_key but names itself in client_metadata.session_id. Account identity scoping compared the key only with client_metadata.session_id, so a fork's key fell into the prompt-cache namespace and reached upstream as a different value from its parent's, and the fork lost the parent's prompt cache. Treat a key that equals either client_metadata.session_id or the client's session-id header as a session key. --- .../service/openai_codex_account_identity.go | 37 +++++++--- .../openai_codex_account_identity_test.go | 74 ++++++++++++++++++- .../openai_codex_turn_metadata_test.go | 4 +- .../openai_gateway_chat_completions.go | 2 +- .../service/openai_gateway_forward.go | 2 +- .../service/openai_gateway_messages.go | 2 +- .../service/openai_gateway_passthrough.go | 2 +- .../service/openai_ws_forwarder_ingress.go | 2 +- .../openai_ws_v2_passthrough_adapter.go | 4 +- 9 files changed, 107 insertions(+), 22 deletions(-) diff --git a/backend/internal/service/openai_codex_account_identity.go b/backend/internal/service/openai_codex_account_identity.go index a7ce166165..39921cd530 100644 --- a/backend/internal/service/openai_codex_account_identity.go +++ b/backend/internal/service/openai_codex_account_identity.go @@ -46,6 +46,15 @@ func codexAccountIdentitySource(c *gin.Context, fallback *Account) *Account { return fallback } +// codexClientSessionID returns the client's own session header, before any +// outbound rewrite. +func codexClientSessionID(c *gin.Context) string { + if c == nil || c.Request == nil { + return "" + } + return extractClientSessionID(c.Request.Header) +} + // codexAccountIdentityNamespace returns a stable, credential-scoped namespace. // Multiple local rows that use the same ChatGPT account intentionally share the // same namespace. Setup tokens use an irreversible bearer fingerprint because @@ -162,7 +171,21 @@ func applyCodexAccountIdentityEmbeddedMetadata(values map[string]any, account *A return true } -func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, account *Account, apiKeyID int64) bool { +// codexPromptCacheKeyKind scopes a prompt_cache_key that names the client's +// session in the session namespace, so it stays equal to the scoped session. +// Codex derives the key from its session-id header, which matches +// client_metadata.session_id except on an ephemeral fork such as thread/sample: +// the fork names itself in the metadata but keeps its parent's header and key. +func codexPromptCacheKeyKind(promptCacheKey, bodySessionID, clientSessionID string) string { + for _, sessionID := range []string{bodySessionID, clientSessionID} { + if strings.TrimSpace(sessionID) != "" && promptCacheKey == sessionID { + return "session" + } + } + return "prompt-cache" +} + +func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, account *Account, apiKeyID int64, clientSessionID string) bool { if requestBody == nil || codexAccountIdentityNamespace(account) == "" { return false } @@ -179,10 +202,7 @@ func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, acco } } if raw, ok := requestBody["prompt_cache_key"].(string); ok && strings.TrimSpace(raw) != "" { - kind := "prompt-cache" - if strings.TrimSpace(originalBodySessionID) != "" && raw == originalBodySessionID { - kind = "session" - } + kind := codexPromptCacheKeyKind(raw, originalBodySessionID, clientSessionID) next := scopeCodexAccountIdentityValue(account, apiKeyID, kind, raw) if next != raw { requestBody["prompt_cache_key"] = next @@ -195,7 +215,7 @@ func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, acco // applyCodexAccountIdentityClientMetadataRaw scopes only the small identity // subobjects with gjson/sjson. The passthrough hot path never unmarshals the // potentially multi-megabyte request body. -func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, apiKeyID int64) ([]byte, bool, error) { +func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, apiKeyID int64, clientSessionID string) ([]byte, bool, error) { if len(body) == 0 || codexAccountIdentityNamespace(account) == "" { return body, false, nil } @@ -232,10 +252,7 @@ func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, a } if promptCacheKey := gjson.GetBytes(body, "prompt_cache_key"); promptCacheKey.Type == gjson.String && strings.TrimSpace(promptCacheKey.String()) != "" { raw := promptCacheKey.String() - kind := "prompt-cache" - if strings.TrimSpace(originalBodySessionID) != "" && raw == originalBodySessionID { - kind = "session" - } + kind := codexPromptCacheKeyKind(raw, originalBodySessionID, clientSessionID) scoped := scopeCodexAccountIdentityValue(account, apiKeyID, kind, raw) if scoped != raw { rewritten, err := sjson.SetBytes(next, "prompt_cache_key", scoped) diff --git a/backend/internal/service/openai_codex_account_identity_test.go b/backend/internal/service/openai_codex_account_identity_test.go index ffceba2d39..e0e864beb7 100644 --- a/backend/internal/service/openai_codex_account_identity_test.go +++ b/backend/internal/service/openai_codex_account_identity_test.go @@ -4,13 +4,17 @@ import ( "bytes" "context" "encoding/json" + "io" "net/http" "net/http/httptest" + "strings" "testing" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) type codexAccountIdentityRepoStub struct { @@ -27,13 +31,13 @@ func TestCodexRequestBodyIdentityNamespaceIsStablePerOAuthAccount(t *testing.T) account11 := &Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-11"}} account19 := &Account{ID: 19, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-19"}} - first, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77) + first, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77, "") require.NoError(t, err) require.True(t, changed) - firstAgain, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77) + firstAgain, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77, "") require.NoError(t, err) require.True(t, changed) - second, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account19, 77) + second, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account19, 77, "") require.NoError(t, err) require.True(t, changed) require.JSONEq(t, string(first), string(firstAgain)) @@ -228,3 +232,67 @@ func TestBuildUpstreamRequestNamespacesCodexIdentityByOAuthAccount(t *testing.T) } require.GreaterOrEqual(t, checked, 5, "test must exercise the real outbound identity surface") } + +// An ephemeral Codex fork, such as thread/sample, names itself in +// client_metadata.session_id but keeps its parent's session-id header and +// prompt_cache_key. Upstream, the fork must keep the parent's cache key. +func TestCodexForkKeepsParentPromptCacheKeyUpstream(t *testing.T) { + for _, passthrough := range []bool{false, true} { + t.Run(map[bool]string{false: "transformed", true: "passthrough"}[passthrough], func(t *testing.T) { + gin.SetMode(gin.TestMode) + forward := func(promptCacheKey, bodySessionID string) (http.Header, []byte) { + t.Helper() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.167.0") + c.Request.Header.Set("originator", "codex_cli_rs") + c.Request.Header.Set("session-id", "parent-session") + body := []byte(`{"model":"gpt-5.6-sol","stream":false,"input":[{"type":"message","role":"user","content":"hi"}]}`) + body, err := sjson.SetBytes(body, "prompt_cache_key", promptCacheKey) + require.NoError(t, err) + body, err = sjson.SetBytes(body, "client_metadata.session_id", bodySessionID) + require.NoError(t, err) + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid"}}, + Body: io.NopCloser(strings.NewReader("data: [DONE]\n\n")), + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{}, + httpUpstream: upstream, + toolCorrector: NewCodexToolCorrector(), + } + account := newTestOAuthAccount(4501, map[string]any{"openai_oauth_passthrough": passthrough}) + account.Status = StatusActive + account.Schedulable = true + account.Concurrency = 1 + account.Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"} + + _, err = svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, upstream.lastReq) + return upstream.lastReq.Header, upstream.lastBody + } + + parentHeader, parentBody := forward("parent-session", "parent-session") + parentKey := gjson.GetBytes(parentBody, "prompt_cache_key").String() + require.NotEqual(t, "parent-session", parentKey, "the key is account-scoped") + require.Equal(t, gjson.GetBytes(parentBody, "client_metadata.session_id").String(), parentKey) + + forkHeader, forkBody := forward("parent-session", "fork-session") + require.Equal(t, parentKey, gjson.GetBytes(forkBody, "prompt_cache_key").String(), + "a fork keeps its parent's upstream cache key") + require.Equal(t, parentHeader.Get("session_id"), forkHeader.Get("session_id")) + require.NotEqual(t, + gjson.GetBytes(parentBody, "client_metadata.session_id").String(), + gjson.GetBytes(forkBody, "client_metadata.session_id").String(), + "the fork keeps its own session identity", + ) + + _, customBody := forward("caller-cache-key", "parent-session") + require.NotEqual(t, parentKey, gjson.GetBytes(customBody, "prompt_cache_key").String(), + "a caller-chosen key keeps its own namespace") + }) + } +} diff --git a/backend/internal/service/openai_codex_turn_metadata_test.go b/backend/internal/service/openai_codex_turn_metadata_test.go index a3a5b4773b..94d132f571 100644 --- a/backend/internal/service/openai_codex_turn_metadata_test.go +++ b/backend/internal/service/openai_codex_turn_metadata_test.go @@ -24,7 +24,7 @@ func TestCodexTurnMetadataRewritePreservesHeaderSafeJSON(t *testing.T) { }, "account_body_map": func(t *testing.T, raw string) string { cm := map[string]any{openAIWSTurnMetadataHeader: raw} - require.True(t, applyCodexAccountIdentityClientMetadataMap(map[string]any{"client_metadata": cm}, account, 77)) + require.True(t, applyCodexAccountIdentityClientMetadataMap(map[string]any{"client_metadata": cm}, account, 77, "")) value, ok := cm[openAIWSTurnMetadataHeader].(string) require.True(t, ok) return value @@ -32,7 +32,7 @@ func TestCodexTurnMetadataRewritePreservesHeaderSafeJSON(t *testing.T) { "account_body_raw": func(t *testing.T, raw string) string { body, err := json.Marshal(map[string]any{"client_metadata": map[string]any{openAIWSTurnMetadataHeader: raw}}) require.NoError(t, err) - updated, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account, 77) + updated, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account, 77, "") require.NoError(t, err) require.True(t, changed) return gjson.GetBytes(updated, "client_metadata."+openAIWSTurnMetadataHeader).String() diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index c340de7c49..6a9d773668 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -285,7 +285,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( } else if promptCacheKey != "" { reqBody["prompt_cache_key"] = promptCacheKey } - applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) responsesBody, err = json.Marshal(reqBody) if err != nil { return nil, fmt.Errorf("remarshal after codex transform: %w", err) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index ba7c1beaec..d74ac5c775 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -569,7 +569,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // Account namespace is orthogonal to fingerprint convergence: preserve // each client's identity cardinality, but never reuse it across OAuth // credentials after scheduler failover. - if !isCompactRequest && applyCodexAccountIdentityClientMetadataMap(decoded, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) { + if !isCompactRequest && applyCodexAccountIdentityClientMetadataMap(decoded, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) { markDecodedModified() } stageCodexFingerprintIDs(c, nil) diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..32f9c8aaf7 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -266,7 +266,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( if codexResult.PromptCacheKey != "" { promptCacheKey = codexResult.PromptCacheKey } - applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), apiKeyID) + applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), apiKeyID, codexClientSessionID(c)) delete(reqBody, "prompt_cache_key") if shouldAutoInjectPromptCacheKeyForCompat(upstreamModel) { compatTurnState = s.getOpenAICompatSessionTurnState(ctx, c, account, promptCacheKey) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index bf3debe638..8cb5064869 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -173,7 +173,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( reqStream = false } - accountScopedBody, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(body, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedBody, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(body, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return nil, scopeErr } diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 5d8fffa62f..c3994e3540 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -320,7 +320,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( normalized = next } accountIdentitySourceRaw := append([]byte(nil), normalized...) - accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(normalized, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(normalized, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket identity metadata", scopeErr) } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 71804511eb..22d74f58db 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -761,7 +761,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( firstClientMessage = aliasedBody } } - accountScopedFirst, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(firstClientMessage, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedFirst, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(firstClientMessage, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket identity metadata", scopeErr) } @@ -1015,7 +1015,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } } if isResponseCreate || eventType == "session.update" { - accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(payload, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(payload, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket identity metadata", scopeErr) } From 71ef5770547e16007ea0c41ad94f43698d091d59 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:45:09 +0800 Subject: [PATCH 08/85] perf(gateway): trim per-request JSON work on the Anthropic request path - Skip both cache_control walks with a byte-level precheck when the body has at most 4 cache_control keys, no thinking block and no 1h TTL; skip the block-limit walk when only 1h is present. Bodies containing \u escapes always take the original path. - Replace gjson Array() materialization with Get("0")/ForEach in the beta, toolset, tool-rewrite, web-search and system-preview helpers. - Build the Claude Code mimic debug line lazily; it is only read on credential-scope errors. - Compute the billing-header fingerprint once instead of per block. Differential tests copy the previous implementations verbatim and compare byte for byte across edge cases and 3000 randomized bodies. Batching TTL rewrites with sjson ReplaceInPlace was rejected because it resolves duplicate keys differently. Common ~32KB Claude Code request: enforceCacheControlLimit 100us/21 allocs -> 21.6us/0 allocs; helper set 47.6us/103KB -> 37.9us/69KB; debug line 9.1us/53 allocs -> ~0. --- .../service/gateway_billing_header.go | 7 +- .../service/gateway_claude_oauth_body.go | 31 +- .../internal/service/gateway_count_tokens.go | 2 +- .../gateway_request_json_bench_test.go | 133 ++++++ .../gateway_request_json_equivalence_test.go | 424 ++++++++++++++++++ .../gateway_request_json_legacy_test.go | 170 +++++++ backend/internal/service/gateway_service.go | 72 ++- .../internal/service/gateway_tool_rewrite.go | 50 +-- .../service/gateway_upstream_request.go | 19 +- .../service/gateway_upstream_response.go | 28 +- .../service/gateway_websearch_emulation.go | 29 +- 11 files changed, 899 insertions(+), 66 deletions(-) create mode 100644 backend/internal/service/gateway_request_json_bench_test.go create mode 100644 backend/internal/service/gateway_request_json_equivalence_test.go create mode 100644 backend/internal/service/gateway_request_json_legacy_test.go diff --git a/backend/internal/service/gateway_billing_header.go b/backend/internal/service/gateway_billing_header.go index a794af0d20..fff59baccd 100644 --- a/backend/internal/service/gateway_billing_header.go +++ b/backend/internal/service/gateway_billing_header.go @@ -44,12 +44,17 @@ func syncBillingHeaderVersion(body []byte, userAgent string) []byte { } replacement := "cc_version=" + version + // The fingerprint depends only on the original messages and version, so it + // is the same for every billing block. Compute it lazily, at most once. + fingerprintedReplacement := "" idx := 0 systemResult.ForEach(func(_, item gjson.Result) bool { text := item.Get("text") if text.Exists() && text.Type == gjson.String && strings.HasPrefix(text.String(), "x-anthropic-billing-header") { - fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version) + if fingerprintedReplacement == "" { + fingerprintedReplacement = replacement + "." + computeClaudeCodeFingerprint(body, version) + } newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement) newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement) if newText != text.String() { diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 44e9aaaac1..eb4faac461 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -307,7 +307,8 @@ func normalizeClaudeOAuthRequestBody(body []byte, modelID string, opts claudeOAu // applyToolNameRewriteToBody 同步映射为假名 // - 其他形态(auto/any/none)原样透传 // 如果 body 里完全没有 tools(空数组),tool_choice 没意义时才删除 - if !gjson.GetBytes(out, "tools").IsArray() || len(gjson.GetBytes(out, "tools").Array()) == 0 { + toolsResult := gjson.GetBytes(out, "tools") + if !toolsResult.IsArray() || !toolsResult.Get("0").Exists() { if !isClaude55SignedThinkingModel(modelID) && gjson.GetBytes(out, "tool_choice").Exists() { if next, ok := deleteJSONPathBytes(out, "tool_choice"); ok { out = next @@ -1059,9 +1060,37 @@ func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath, return invalidThinking, messagePaths, toolPaths, systemPaths } +var ( + cacheControlKeyBytes = []byte(`"cache_control"`) + thinkingBlockTypeBytes = []byte(`"thinking"`) + cacheTTL1hJSONBytes = []byte(`"1h"`) + jsonUnicodeEscapeBytes = []byte(`\u`) +) + // enforceCacheControlLimit 让出站 cache_control 满足上游约束: // 先执行块数量限制,再修正 TTL 顺序。 +// +// 大多数请求的 cache_control 块不超过 4 个、没有 thinking 块、也没有 1h TTL, +// 此时两步都是 no-op。用字节级预检查跳过两次 collectCacheControlPaths 遍历。 +// 预检查只会多算(把请求送回原路径),不会漏判;含 \u 转义的 body 可能把 +// 键名或值写成转义形式,字节匹配看不到,因此直接走原路径。 func enforceCacheControlLimit(body []byte) []byte { + if len(body) == 0 { + return body + } + if bytes.Contains(body, jsonUnicodeEscapeBytes) { + return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) + } + if !bytes.Contains(body, cacheControlKeyBytes) { + return body + } + if bytes.Count(body, cacheControlKeyBytes) <= maxCacheControlBlocks && + !bytes.Contains(body, thinkingBlockTypeBytes) { + if !bytes.Contains(body, cacheTTL1hJSONBytes) { + return body + } + return normalizeCacheControlTTLOrder(body) + } return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) } diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index a6a493e25e..9718ef3e05 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -614,7 +614,7 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con filterSonnet55ToolsetBetaHeader(req.Header, body, modelID) if c != nil && tokenType == "oauth" { - c.Set(claudeMimicDebugInfoKey, buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) + c.Set(claudeMimicDebugInfoKey, newClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) } if s.debugClaudeMimicEnabled() { logClaudeMimicDebug(req, body, account, tokenType, mimicClaudeCode) diff --git a/backend/internal/service/gateway_request_json_bench_test.go b/backend/internal/service/gateway_request_json_bench_test.go new file mode 100644 index 0000000000..3ba89900f8 --- /dev/null +++ b/backend/internal/service/gateway_request_json_bench_test.go @@ -0,0 +1,133 @@ +package service + +import ( + "fmt" + "net/http" + "strings" + "testing" +) + +// claudeCodeLikeBody builds a ~32KB request shaped like a Claude Code turn: +// 20 tools, a system prompt, and 40 messages with 4 content blocks each. +func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { + var b strings.Builder + b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`) + for i := 0; i < 20; i++ { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"name":"tool_%d","description":"%s","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}`, i, strings.Repeat("d", 40)) + if i == 19 && cacheControls > 0 { + b.WriteString(`,"cache_control":{"type":"ephemeral"}`) + cacheControls-- + } + b.WriteByte('}') + } + b.WriteString(`],"system":[{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."`) + if cacheControls > 0 { + b.WriteString(`,"cache_control":{"type":"ephemeral"}`) + cacheControls-- + } + b.WriteString(`}],"messages":[`) + for m := 0; m < 40; m++ { + if m > 0 { + b.WriteByte(',') + } + role := "user" + if m%2 == 1 { + role = "assistant" + } + fmt.Fprintf(&b, `{"role":%q,"content":[`, role) + for c := 0; c < 4; c++ { + if c > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"type":"text","text":"%s"`, strings.Repeat("x", 120)) + if m >= 38 && c == 3 && cacheControls > 0 { + ttl := "" + if with1h && m == 39 { + ttl = `,"ttl":"1h"` + } + fmt.Fprintf(&b, `,"cache_control":{"type":"ephemeral"%s}`, ttl) + cacheControls-- + } + b.WriteByte('}') + } + b.WriteString(`]}`) + } + b.WriteString(`]}`) + return []byte(b.String()) +} + +func BenchmarkEnforceCacheControlLimit(b *testing.B) { + cases := []struct { + name string + body []byte + }{ + {"common_4cc_no1h", claudeCodeLikeBody(4, false)}, + {"with_1h", claudeCodeLikeBody(4, true)}, + } + for _, tc := range cases { + b.Run(tc.name+"/legacy", func(b *testing.B) { + b.SetBytes(int64(len(tc.body))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = legacyEnforceCacheControlLimit(tc.body) + } + }) + b.Run(tc.name+"/optimized", func(b *testing.B) { + b.SetBytes(int64(len(tc.body))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = enforceCacheControlLimit(tc.body) + } + }) + } +} + +func BenchmarkRequestToolHelpers(b *testing.B) { + body := claudeCodeLikeBody(4, false) + b.Run("legacy", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = legacyRequestNeedsBetaFeatures(body) + _ = legacyFilterSonnet55ToolsetBeta("fine-grained-tool-streaming-2025-05-14", body, "claude-sonnet-5-5") + _ = legacyIsOnlyWebSearchToolInBody(body) + _ = legacyBuildToolNameRewriteFromBody(body) + _ = legacyApplyToolsLastCacheBreakpoint(body) + _ = legacyExtractSystemPreviewFromBody(body) + } + }) + b.Run("optimized", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = requestNeedsBetaFeatures(body) + _ = filterSonnet55ToolsetBeta("fine-grained-tool-streaming-2025-05-14", body, "claude-sonnet-5-5") + _ = isOnlyWebSearchToolInBody(body) + _ = buildToolNameRewriteFromBody(body) + _ = applyToolsLastCacheBreakpoint(body) + _ = extractSystemPreviewFromBody(body) + } + }) +} + +func BenchmarkClaudeMimicDebugLine(b *testing.B) { + req, _ := http.NewRequest(http.MethodPost, "https://api.anthropic.com/v1/messages?beta=true", nil) + for _, h := range []string{"User-Agent", "X-App", "Anthropic-Version", "Anthropic-Beta", "X-Stainless-Lang", "X-Stainless-Os", "Authorization", "Content-Type", "Accept"} { + req.Header.Set(h, "value-"+h) + } + body := claudeCodeLikeBody(4, false) + account := &Account{ID: 1, Name: "acc"} + b.Run("eager", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = buildClaudeMimicDebugLine(req, body, account, "oauth", true) + } + }) + b.Run("lazy_unused", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = newClaudeMimicDebugLine(req, body, account, "oauth", true) + } + }) +} diff --git a/backend/internal/service/gateway_request_json_equivalence_test.go b/backend/internal/service/gateway_request_json_equivalence_test.go new file mode 100644 index 0000000000..1d78c15c0e --- /dev/null +++ b/backend/internal/service/gateway_request_json_equivalence_test.go @@ -0,0 +1,424 @@ +package service + +import ( + "bytes" + "fmt" + "math/rand" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// legacyEnforceCacheControlLimit / legacyNormalizeCacheControlTTLOrder / +// legacyForceEphemeralCacheControlTTL are verbatim copies of the +// implementations before the fast path was introduced. The tests below compare +// the optimized code against them byte for byte. +func legacyEnforceCacheControlLimit(body []byte) []byte { + return legacyNormalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) +} + +func legacyNormalizeCacheControlTTLOrder(body []byte) []byte { + _, messagePaths, toolPaths, systemPaths := collectCacheControlPaths(body) + paths := make([]string, 0, len(toolPaths)+len(systemPaths)+len(messagePaths)+1) + paths = append(paths, toolPaths...) + paths = append(paths, systemPaths...) + paths = append(paths, messagePaths...) + if gjson.GetBytes(body, "cache_control").Exists() { + paths = append(paths, "cache_control") + } + last1h := -1 + for i, path := range paths { + if gjson.GetBytes(body, path+".ttl").String() == cacheTTLTarget1h { + last1h = i + } + } + out := body + for _, path := range paths[:last1h+1] { + cc := gjson.GetBytes(out, path) + if cc.Get("type").String() != "ephemeral" || cc.Get("ttl").String() == cacheTTLTarget1h { + continue + } + if next, err := sjson.SetBytes(out, path+".ttl", cacheTTLTarget1h); err == nil { + out = next + } + } + return out +} + +func cacheControlEquivalenceCases() map[string]string { + return map[string]string{ + "empty": ``, + "no_cc": `{"model":"claude","messages":[{"role":"user","content":"hi"}]}`, + "one_cc": `{"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, + "four_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "five_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}},{"name":"b","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "thinking_cc": `{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, + "thinking_text": `{"messages":[{"role":"user","content":[{"type":"text","text":"thinking about it","cache_control":{"type":"ephemeral"}}]}]}`, + "ttl_order": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"5m"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "ttl_all_1h": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "top_level_1h": `{"cache_control":{"type":"ephemeral","ttl":"1h"},"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, + "1h_in_text": `{"system":[{"type":"text","text":"\"1h\"","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"1h"}]}`, + "escaped_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache\u005fcontrol":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, + "escaped_ttl": `{"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"\u0031h"}}]}]}`, + "escaped_think": `{"messages":[{"role":"assistant","content":[{"type":"\u0074hinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, + "non_ephemeral": `{"tools":[{"name":"a","cache_control":{"type":"persistent"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "cc_in_string": `{"messages":[{"role":"user","content":"please explain \"cache_control\" and \"thinking\""}]}`, + "duplicate_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"},"cache_control":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, + "invalid_json": `{"messages":[`, + } +} + +func TestEnforceCacheControlLimitMatchesLegacy(t *testing.T) { + for name, raw := range cacheControlEquivalenceCases() { + t.Run(name, func(t *testing.T) { + body := []byte(raw) + want := legacyEnforceCacheControlLimit(append([]byte(nil), body...)) + got := enforceCacheControlLimit(append([]byte(nil), body...)) + require.Equal(t, string(want), string(got)) + }) + } +} + +func TestEnforceCacheControlLimitMatchesLegacyRandomized(t *testing.T) { + rng := rand.New(rand.NewSource(20261111)) + for i := 0; i < 3000; i++ { + body := randomCacheControlBody(rng) + want := legacyEnforceCacheControlLimit(append([]byte(nil), body...)) + got := enforceCacheControlLimit(append([]byte(nil), body...)) + require.Equal(t, string(want), string(got), "case %d body=%s", i, body) + } +} + +func TestEnforceCacheControlLimitDoesNotMutateInput(t *testing.T) { + for name, raw := range cacheControlEquivalenceCases() { + t.Run(name, func(t *testing.T) { + body := []byte(raw) + before := append([]byte(nil), body...) + _ = enforceCacheControlLimit(body) + require.Equal(t, string(before), string(body)) + }) + } +} + +func TestNormalizeCacheControlTTLOrderMatchesLegacy(t *testing.T) { + rng := rand.New(rand.NewSource(7)) + cases := cacheControlEquivalenceCases() + for i := 0; i < 2000; i++ { + cases[fmt.Sprintf("random_%d", i)] = string(randomCacheControlBody(rng)) + } + for name, raw := range cases { + body := []byte(raw) + before := append([]byte(nil), body...) + want := legacyNormalizeCacheControlTTLOrder(append([]byte(nil), body...)) + got := normalizeCacheControlTTLOrder(body) + require.Equal(t, string(want), string(got), name) + require.Equal(t, string(before), string(body), "%s: input must not be mutated", name) + } +} + +func TestForceEphemeralCacheControlTTLDoesNotMutateInput(t *testing.T) { + body := []byte(`{"cache_control":{"type":"ephemeral"},"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`) + before := append([]byte(nil), body...) + got := forceEphemeralCacheControlTTL(body, cacheTTLTarget1h) + require.Equal(t, string(before), string(body)) + require.Equal(t, 4, strings.Count(string(got), `"ttl":"1h"`)) + require.True(t, gjson.ValidBytes(got)) +} + +func randomCacheControlBody(rng *rand.Rand) []byte { + cc := func() string { + switch rng.Intn(7) { + case 0: + return `,"cache_control":{"type":"ephemeral"}` + case 1: + return `,"cache_control":{"type":"ephemeral","ttl":"5m"}` + case 2: + return `,"cache_control":{"type":"ephemeral","ttl":"1h"}` + case 3: + return `,"cache_control":{"type":"persistent","ttl":"1h"}` + default: + return "" + } + } + var b bytes.Buffer + b.WriteString(`{"model":"claude-sonnet"`) + if rng.Intn(5) == 0 { + b.WriteString(`,"cache_control":{"type":"ephemeral","ttl":"1h"}`) + } + if rng.Intn(2) == 0 { + b.WriteString(`,"tools":[`) + n := rng.Intn(4) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"name":"tool_%d"%s}`, i, cc()) + } + b.WriteByte(']') + } + if rng.Intn(2) == 0 { + b.WriteString(`,"system":[`) + n := rng.Intn(3) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"type":"text","text":"sys %d"%s}`, i, cc()) + } + b.WriteByte(']') + } + b.WriteString(`,"messages":[`) + m := rng.Intn(4) + for i := 0; i < m; i++ { + if i > 0 { + b.WriteByte(',') + } + b.WriteString(`{"role":"user","content":[`) + c := rng.Intn(3) + 1 + for j := 0; j < c; j++ { + if j > 0 { + b.WriteByte(',') + } + blockType := "text" + if rng.Intn(6) == 0 { + blockType = "thinking" + } + fmt.Fprintf(&b, `{"type":%q,"text":"m%d-%d"%s}`, blockType, i, j, cc()) + } + b.WriteString(`]}`) + } + b.WriteString(`]}`) + return b.Bytes() +} + +// ---- legacy copies of the array-materializing helpers ---- + +func legacyIsOnlyWebSearchToolInBody(body []byte) bool { + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return false + } + arr := tools.Array() + if len(arr) != 1 { + return false + } + return isWebSearchToolJSON(arr[0]) +} + +func legacyExtractSearchQueryFromBody(body []byte) string { + messages := gjson.GetBytes(body, "messages") + if !messages.IsArray() { + return "" + } + arr := messages.Array() + if len(arr) == 0 { + return "" + } + lastMsg := arr[len(arr)-1] + if lastMsg.Get("role").String() != "user" { + return "" + } + content := lastMsg.Get("content") + if content.Type == gjson.String { + return content.String() + } + if content.IsArray() { + for _, block := range content.Array() { + if block.Get("type").String() == "text" { + if text := block.Get("text").String(); text != "" { + return text + } + } + } + } + return "" +} + +func legacyExtractSystemPreviewFromBody(body []byte) string { + if len(body) == 0 { + return "" + } + sys := gjson.GetBytes(body, "system") + if !sys.Exists() { + return "" + } + switch { + case sys.IsArray(): + for _, item := range sys.Array() { + if !item.IsObject() { + continue + } + if strings.EqualFold(item.Get("type").String(), "text") { + if t := item.Get("text").String(); strings.TrimSpace(t) != "" { + return t + } + } + } + return "" + case sys.Type == gjson.String: + return sys.String() + default: + return "" + } +} + +func legacyRequestNeedsBetaFeatures(body []byte) bool { + tools := gjson.GetBytes(body, "tools") + if tools.Exists() && tools.IsArray() && len(tools.Array()) > 0 { + return true + } + thinkingType := gjson.GetBytes(body, "thinking.type").String() + return strings.EqualFold(thinkingType, "enabled") || strings.EqualFold(thinkingType, "adaptive") +} + +func requestHelperEquivalenceBodies() []string { + return []string{ + ``, + `{}`, + `{"tools":[]}`, + `{"tools":{}}`, + `{"tools":null}`, + `{"tools":[null]}`, + `{"tools":[{"type":"web_search_20250305","name":"web_search"}]}`, + `{"tools":[{"name":"web_search"}]}`, + `{"tools":[{"name":"google_search"}]}`, + `{"tools":[{"type":"web_search_20250305"},{"name":"bash"}]}`, + `{"tools":[{"name":"bash"}]}`, + `{"tools":[{"type":"computer_toolset_20260801"},{"type":"x"}]}`, + `{"tools":[{"type":"x"},{"type":"browser_toolset_20260801"}]}`, + `{"thinking":{"type":"adaptive"}}`, + `{"messages":[]}`, + `{"messages":[{"role":"assistant","content":"x"}]}`, + `{"messages":[{"role":"user","content":"hello"}]}`, + `{"messages":[{"role":"user","content":[{"type":"image"},{"type":"text","text":""},{"type":"text","text":"q"}]}]}`, + `{"messages":[{"role":"user","content":"a"},{"role":"user","content":[{"type":"text","text":"last"}]}]}`, + `{"messages":[{"role":"user","content":"a"},null]}`, + `{"system":"plain system"}`, + `{"system":[]}`, + `{"system":[1,"x",{"type":"TEXT","text":" "},{"type":"text","text":"first"},{"type":"text","text":"second"}]}`, + `{"system":{"type":"text"}}`, + `{"messages":[`, + } +} + +func TestRequestJSONHelpersMatchLegacy(t *testing.T) { + for _, raw := range requestHelperEquivalenceBodies() { + body := []byte(raw) + require.Equal(t, legacyIsOnlyWebSearchToolInBody(body), isOnlyWebSearchToolInBody(body), "isOnlyWebSearchToolInBody %s", raw) + require.Equal(t, legacyExtractSearchQueryFromBody(body), extractSearchQueryFromBody(body), "extractSearchQueryFromBody %s", raw) + require.Equal(t, legacyExtractSystemPreviewFromBody(body), extractSystemPreviewFromBody(body), "extractSystemPreviewFromBody %s", raw) + require.Equal(t, legacyRequestNeedsBetaFeatures(body), requestNeedsBetaFeatures(body), "requestNeedsBetaFeatures %s", raw) + } +} + +func TestClaudeMimicDebugLineIsLazyAndMatchesEager(t *testing.T) { + req, err := http.NewRequest(http.MethodPost, "https://api.anthropic.com/v1/messages", nil) + require.NoError(t, err) + req.Header.Set("User-Agent", "claude-cli/2.1.200") + req.Header.Set("Authorization", "Bearer secret-token") + body := []byte(`{"metadata":{"user_id":"user_1"},"system":[{"type":"text","text":"You are Claude Code"}]}`) + account := &Account{ID: 7, Name: "acc"} + + want := buildClaudeMimicDebugLine(req, body, account, "oauth", true) + lazy := newClaudeMimicDebugLine(req, body, account, "oauth", true) + require.Empty(t, lazy.line, "line must not be built eagerly") + require.Equal(t, want, lazy.String()) + require.Equal(t, want, lazy.String(), "second call returns cached line") + require.Nil(t, lazy.req, "request reference is released after building") + require.Nil(t, lazy.body, "body reference is released after building") + + c := &ginContextStub{values: map[string]any{claudeMimicDebugInfoKey: newClaudeMimicDebugLine(req, body, account, "oauth", true)}} + require.Equal(t, want, claudeMimicDebugLineFromContext(c)) + c.values[claudeMimicDebugInfoKey] = "legacy string" + require.Equal(t, "legacy string", claudeMimicDebugLineFromContext(c)) + delete(c.values, claudeMimicDebugInfoKey) + require.Empty(t, claudeMimicDebugLineFromContext(c)) + require.Empty(t, claudeMimicDebugLineFromContext(nil)) +} + +type ginContextStub struct { + values map[string]any +} + +func (c *ginContextStub) Get(key string) (any, bool) { + v, ok := c.values[key] + return v, ok +} + +func toolBodiesForEquivalence() []string { + return []string{ + `{}`, + `{"tools":[]}`, + `{"tools":{}}`, + `{"tools":[{"name":"bash"}]}`, + `{"tools":[{"name":"sessions_list"},{"name":"session_get","type":"custom"},{"name":"web_search","type":"web_search_20250305"}]}`, + `{"tools":[{"name":"a"},{"name":"b"},{"name":"c"},{"name":"d"},{"name":"e"},{"name":"f"},{"name":"g"}],"tool_choice":{"type":"tool","name":"c"}}`, + `{"tools":[{"name":"a","defer_loading":true,"cache_control":{"type":"ephemeral"}},{"name":"b"}]}`, + `{"tools":[{"name":"a"},{"name":"b","custom":{"defer_loading":true},"cache_control":{"type":"ephemeral"}}]}`, + `{"tools":[{"name":"a","defer_loading":true},{"name":"b","defer_loading":true}]}`, + `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}`, + `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}]}`, + `{"tools":[{"name":"a","defer_loading":"true","cache_control":{"type":"ephemeral"}}]}`, + `{"tools":[{"type":"computer_toolset_20260801"}]}`, + `{"tools":[{"type":"browser_toolset_20260801"},{"type":"computer_toolset_20260801"}]}`, + } +} + +func TestToolHelpersMatchLegacy(t *testing.T) { + headers := []string{"", "fine-grained-tool-streaming-2025-05-14", "a,fine-grained-tool-streaming-2025-05-14,b"} + models := []string{"claude-sonnet-5-5", "claude-haiku-5-5@20260101", "claude-opus-5-5"} + for _, raw := range toolBodiesForEquivalence() { + body := []byte(raw) + + requireEquivalentToolNameRewrite(t, legacyBuildToolNameRewriteFromBody(body), buildToolNameRewriteFromBody(body), raw) + require.Equal(t, + string(legacyApplyToolsLastCacheBreakpoint(append([]byte(nil), body...))), + string(applyToolsLastCacheBreakpoint(append([]byte(nil), body...))), raw) + require.Equal(t, + string(legacyStripDeferredToolCacheControl(append([]byte(nil), body...))), + string(stripDeferredToolCacheControl(append([]byte(nil), body...))), raw) + for _, h := range headers { + for _, m := range models { + require.Equal(t, legacyFilterSonnet55ToolsetBeta(h, body, m), filterSonnet55ToolsetBeta(h, body, m), "%s %s %s", raw, h, m) + } + } + } +} + +func TestSyncBillingHeaderVersionMatchesLegacy(t *testing.T) { + bodies := []string{ + `{"system":"plain"}`, + `{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.0.0.abc; cc_entrypoint=cli"}],"messages":[{"role":"user","content":"hello world from a long prompt"}]}`, + `{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.0.0; cc_entrypoint=cli"},{"type":"text","text":"x-anthropic-billing-header: cc_version=1.0.0.xyz"}],"messages":[{"role":"user","content":[{"type":"text","text":"你好世界🙂"}]}]}`, + `{"system":[{"type":"text","text":"other"}]}`, + } + for _, raw := range bodies { + for _, ua := range []string{"", "claude-cli/2.1.200 (external, cli)", "curl/8"} { + want := legacySyncBillingHeaderVersion(append([]byte(nil), raw...), ua) + got := syncBillingHeaderVersion(append([]byte(nil), raw...), ua) + require.Equal(t, string(want), string(got), "%s ua=%s", raw, ua) + } + } +} + +// ReverseOrdered is built from map iteration, so entries with equal fake-name +// length come out in random order (both before and after this change). Equal +// length distinct names cannot be substrings of each other, so that order does +// not affect replacement; compare the set and the length ordering instead. +func requireEquivalentToolNameRewrite(t *testing.T, want, got *ToolNameRewrite, msg string) { + t.Helper() + if want == nil || got == nil { + require.Equal(t, want, got, msg) + return + } + require.Equal(t, want.Forward, got.Forward, msg) + require.Equal(t, want.Reverse, got.Reverse, msg) + require.ElementsMatch(t, want.ReverseOrdered, got.ReverseOrdered, msg) + for i := 1; i < len(got.ReverseOrdered); i++ { + require.GreaterOrEqual(t, len(got.ReverseOrdered[i-1][0]), len(got.ReverseOrdered[i][0]), msg) + } +} diff --git a/backend/internal/service/gateway_request_json_legacy_test.go b/backend/internal/service/gateway_request_json_legacy_test.go new file mode 100644 index 0000000000..a57dc75bd8 --- /dev/null +++ b/backend/internal/service/gateway_request_json_legacy_test.go @@ -0,0 +1,170 @@ +package service + +import ( + "fmt" + "sort" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/claude" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Verbatim legacy copies used only by equivalence tests. + +func legacyBuildToolNameRewriteFromBody(body []byte) *ToolNameRewrite { + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return nil + } + + mimicableNames := make([]string, 0) + toolsArr := tools.Array() + for _, t := range toolsArr { + if !shouldMimicToolName(t.Get("type").String()) { + continue + } + name := t.Get("name").String() + if name == "" { + continue + } + mimicableNames = append(mimicableNames, name) + } + + dynamic := buildDynamicToolMap(mimicableNames) + + rw := &ToolNameRewrite{ + Forward: make(map[string]string), + Reverse: make(map[string]string), + } + for _, name := range mimicableNames { + fake := sanitizeToolName(name, dynamic) + if fake == name { + continue + } + rw.Forward[name] = fake + rw.Reverse[fake] = name + } + if len(rw.Forward) == 0 { + return nil + } + + rw.ReverseOrdered = make([][2]string, 0, len(rw.Reverse)) + for fake, real := range rw.Reverse { + rw.ReverseOrdered = append(rw.ReverseOrdered, [2]string{fake, real}) + } + sort.SliceStable(rw.ReverseOrdered, func(i, j int) bool { + return len(rw.ReverseOrdered[i][0]) > len(rw.ReverseOrdered[j][0]) + }) + + return rw +} + +func legacyApplyToolsLastCacheBreakpoint(body []byte) []byte { + body = legacyStripDeferredToolCacheControl(body) + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + arr := tools.Array() + if len(arr) == 0 { + return body + } + lastIdx := -1 + for idx, tool := range arr { + if isDeferredLoadingTool(tool) { + continue + } + lastIdx = idx + } + if lastIdx == -1 { + return body + } + + existingCC := arr[lastIdx].Get("cache_control") + + if existingCC.Exists() && existingCC.Get("ttl").String() != "" { + return body + } + + if existingCC.Exists() { + if next, err := sjson.SetBytes(body, fmt.Sprintf("tools.%d.cache_control.ttl", lastIdx), claude.DefaultCacheControlTTL); err == nil { + body = next + } + return body + } + + raw := fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, claude.DefaultCacheControlTTL) + if next, err := sjson.SetRawBytes(body, fmt.Sprintf("tools.%d.cache_control", lastIdx), []byte(raw)); err == nil { + body = next + } + return body +} + +func legacyStripDeferredToolCacheControl(body []byte) []byte { + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + for idx, tool := range tools.Array() { + if !isDeferredLoadingTool(tool) || !tool.Get("cache_control").Exists() { + continue + } + if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil { + body = next + } + } + return body +} + +func legacyFilterSonnet55ToolsetBeta(header string, body []byte, modelID string) string { + if at := strings.IndexByte(modelID, '@'); at >= 0 { + modelID = modelID[:at] // Vertex's dated model ID + } + if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) { + return header + } + for _, tool := range gjson.GetBytes(body, "tools").Array() { + switch tool.Get("type").String() { + case "computer_toolset_20260801", "browser_toolset_20260801": + if !containsBetaToken(header, claude.BetaFineGrainedToolStreaming) { + return header + } + return stripBetaTokensWithSet(header, map[string]struct{}{claude.BetaFineGrainedToolStreaming: {}}) + } + } + return header +} + +func legacySyncBillingHeaderVersion(body []byte, userAgent string) []byte { + version := ExtractCLIVersion(userAgent) + if version == "" { + return body + } + + systemResult := gjson.GetBytes(body, "system") + if !systemResult.Exists() || !systemResult.IsArray() { + return body + } + + replacement := "cc_version=" + version + idx := 0 + systemResult.ForEach(func(_, item gjson.Result) bool { + text := item.Get("text") + if text.Exists() && text.Type == gjson.String && + strings.HasPrefix(text.String(), "x-anthropic-billing-header") { + fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version) + newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement) + newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement) + if newText != text.String() { + if updated, err := sjson.SetBytes(body, fmt.Sprintf("system.%d.text", idx), newText); err == nil { + body = updated + } + } + } + idx++ + return true + }) + + return body +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..fb38d299a1 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -15,6 +15,7 @@ import ( "sort" "strconv" "strings" + "sync" "sync/atomic" "time" "unsafe" @@ -303,17 +304,20 @@ func extractSystemPreviewFromBody(body []byte) string { switch { case sys.IsArray(): - for _, item := range sys.Array() { + var preview string + sys.ForEach(func(_, item gjson.Result) bool { if !item.IsObject() { - continue + return true } if strings.EqualFold(item.Get("type").String(), "text") { if t := item.Get("text").String(); strings.TrimSpace(t) != "" { - return t + preview = t + return false } } - } - return "" + return true + }) + return preview case sys.Type == gjson.String: return sys.String() default: @@ -385,6 +389,64 @@ func buildClaudeMimicDebugLine(req *http.Request, body []byte, account *Account, ) } +// claudeMimicDebugLine defers building the diagnostics line until an error +// path actually needs it. The line is read only on Claude Code credential-scope +// errors, so building it eagerly cost every OAuth request a header walk, a +// system-prompt scan and several fmt.Sprintf calls for nothing. +type claudeMimicDebugLine struct { + once sync.Once + req *http.Request + body []byte + account *Account + tokenType string + mimicClaudeCode bool + line string +} + +func newClaudeMimicDebugLine(req *http.Request, body []byte, account *Account, tokenType string, mimicClaudeCode bool) *claudeMimicDebugLine { + return &claudeMimicDebugLine{ + req: req, + body: body, + account: account, + tokenType: tokenType, + mimicClaudeCode: mimicClaudeCode, + } +} + +func (l *claudeMimicDebugLine) String() string { + if l == nil { + return "" + } + l.once.Do(func() { + l.line = buildClaudeMimicDebugLine(l.req, l.body, l.account, l.tokenType, l.mimicClaudeCode) + // Drop references so the request/body are not retained after use. + l.req, l.body, l.account = nil, nil, nil + }) + return l.line +} + +// claudeMimicDebugLineFromContext returns the stored diagnostics line, building +// it on first use. It also accepts a plain string for compatibility. +func claudeMimicDebugLineFromContext(c interface { + Get(string) (any, bool) +}) string { + if c == nil { + return "" + } + v, ok := c.Get(claudeMimicDebugInfoKey) + if !ok { + return "" + } + switch line := v.(type) { + case *claudeMimicDebugLine: + return line.String() + case string: + return line + default: + return "" + } +} + func logClaudeMimicDebug(req *http.Request, body []byte, account *Account, tokenType string, mimicClaudeCode bool) { line := buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode) if line == "" { diff --git a/backend/internal/service/gateway_tool_rewrite.go b/backend/internal/service/gateway_tool_rewrite.go index c3e1d8da7f..05b0b77f1c 100644 --- a/backend/internal/service/gateway_tool_rewrite.go +++ b/backend/internal/service/gateway_tool_rewrite.go @@ -128,17 +128,15 @@ func buildToolNameRewriteFromBody(body []byte) *ToolNameRewrite { } mimicableNames := make([]string, 0) - toolsArr := tools.Array() - for _, t := range toolsArr { + tools.ForEach(func(_, t gjson.Result) bool { if !shouldMimicToolName(t.Get("type").String()) { - continue + return true } - name := t.Get("name").String() - if name == "" { - continue + if name := t.Get("name").String(); name != "" { + mimicableNames = append(mimicableNames, name) } - mimicableNames = append(mimicableNames, name) - } + return true + }) dynamic := buildDynamicToolMap(mimicableNames) @@ -269,22 +267,22 @@ func applyToolsLastCacheBreakpoint(body []byte) []byte { if !tools.IsArray() { return body } - arr := tools.Array() - if len(arr) == 0 { - return body - } + idx := 0 lastIdx := -1 - for idx, tool := range arr { - if isDeferredLoadingTool(tool) { - continue + lastTool := gjson.Result{} + tools.ForEach(func(_, tool gjson.Result) bool { + if !isDeferredLoadingTool(tool) { + lastIdx = idx + lastTool = tool } - lastIdx = idx - } + idx++ + return true + }) if lastIdx == -1 { return body } - existingCC := arr[lastIdx].Get("cache_control") + existingCC := lastTool.Get("cache_control") if existingCC.Exists() && existingCC.Get("ttl").String() != "" { return body @@ -316,14 +314,16 @@ func stripDeferredToolCacheControl(body []byte) []byte { if !tools.IsArray() { return body } - for idx, tool := range tools.Array() { - if !isDeferredLoadingTool(tool) || !tool.Get("cache_control").Exists() { - continue + idx := 0 + tools.ForEach(func(_, tool gjson.Result) bool { + if isDeferredLoadingTool(tool) && tool.Get("cache_control").Exists() { + if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil { + body = next + } } - if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil { - body = next - } - } + idx++ + return true + }) return body } diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index beb6fc47e7..a159c867bd 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -248,7 +248,7 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex // Always capture a compact fingerprint line for later error diagnostics. // We only print it when needed (or when the explicit debug flag is enabled). if c != nil && tokenType == "oauth" { - c.Set(claudeMimicDebugInfoKey, buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) + c.Set(claudeMimicDebugInfoKey, newClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) } if s.debugClaudeMimicEnabled() { logClaudeMimicDebug(req, body, account, tokenType, mimicClaudeCode) @@ -441,7 +441,7 @@ func (s *GatewayService) getBetaHeader(modelID string, clientBetaHeader string) func requestNeedsBetaFeatures(body []byte) bool { tools := gjson.GetBytes(body, "tools") - if tools.Exists() && tools.IsArray() && len(tools.Array()) > 0 { + if tools.Exists() && tools.IsArray() && tools.Get("0").Exists() { return true } thinkingType := gjson.GetBytes(body, "thinking.type").String() @@ -470,9 +470,18 @@ func filterSonnet55ToolsetBeta(header string, body []byte, modelID string) strin if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) { return header } - for _, tool := range gjson.GetBytes(body, "tools").Array() { - switch tool.Get("type").String() { - case "computer_toolset_20260801", "browser_toolset_20260801": + tools := gjson.GetBytes(body, "tools") + if tools.IsArray() { + matched := false + tools.ForEach(func(_, tool gjson.Result) bool { + switch tool.Get("type").String() { + case "computer_toolset_20260801", "browser_toolset_20260801": + matched = true + return false + } + return true + }) + if matched { if !containsBetaToken(header, claude.BetaFineGrainedToolStreaming) { return header } diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 85b415e5cf..5425d72bb8 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -383,14 +383,12 @@ func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Res // Print a compact upstream request fingerprint when we hit the Claude Code OAuth // credential scope error. This avoids requiring env-var tweaks in a fixed deploy. if isClaudeCodeCredentialScopeError(upstreamMsg) && c != nil { - if v, ok := c.Get(claudeMimicDebugInfoKey); ok { - if line, ok := v.(string); ok && strings.TrimSpace(line) != "" { - logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", - resp.StatusCode, - resp.Header.Get("x-request-id"), - line, - ) - } + if line := claudeMimicDebugLineFromContext(c); strings.TrimSpace(line) != "" { + logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", + resp.StatusCode, + resp.Header.Get("x-request-id"), + line, + ) } } @@ -572,14 +570,12 @@ func (s *GatewayService) handleRetryExhaustedError(ctx context.Context, resp *ht upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) if isClaudeCodeCredentialScopeError(upstreamMsg) && c != nil { - if v, ok := c.Get(claudeMimicDebugInfoKey); ok { - if line, ok := v.(string); ok && strings.TrimSpace(line) != "" { - logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", - resp.StatusCode, - resp.Header.Get("x-request-id"), - line, - ) - } + if line := claudeMimicDebugLineFromContext(c); strings.TrimSpace(line) != "" { + logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", + resp.StatusCode, + resp.Header.Get("x-request-id"), + line, + ) } } diff --git a/backend/internal/service/gateway_websearch_emulation.go b/backend/internal/service/gateway_websearch_emulation.go index 8425109018..c359433d2d 100644 --- a/backend/internal/service/gateway_websearch_emulation.go +++ b/backend/internal/service/gateway_websearch_emulation.go @@ -100,11 +100,10 @@ func isOnlyWebSearchToolInBody(body []byte) bool { if !tools.IsArray() { return false } - arr := tools.Array() - if len(arr) != 1 { + if !tools.Get("0").Exists() || tools.Get("1").Exists() { return false } - return isWebSearchToolJSON(arr[0]) + return isWebSearchToolJSON(tools.Get("0")) } func isWebSearchToolJSON(tool gjson.Result) bool { @@ -125,12 +124,14 @@ func extractSearchQueryFromBody(body []byte) string { if !messages.IsArray() { return "" } - arr := messages.Array() - if len(arr) == 0 { - return "" - } - lastMsg := arr[len(arr)-1] - if lastMsg.Get("role").String() != "user" { + var lastMsg gjson.Result + found := false + messages.ForEach(func(_, msg gjson.Result) bool { + lastMsg = msg + found = true + return true + }) + if !found || lastMsg.Get("role").String() != "user" { return "" } return extractWebSearchTextFromContent(lastMsg.Get("content")) @@ -141,13 +142,17 @@ func extractWebSearchTextFromContent(content gjson.Result) string { return content.String() } if content.IsArray() { - for _, block := range content.Array() { + var result string + content.ForEach(func(_, block gjson.Result) bool { if block.Get("type").String() == "text" { if text := block.Get("text").String(); text != "" { - return text + result = text + return false } } - } + return true + }) + return result } return "" } From a8481f0dec1bd319a1cdefec79363ccf7ee8ce2e Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:54:37 +0800 Subject: [PATCH 09/85] test(gateway): satisfy errcheck in request JSON tests --- .../gateway_request_json_bench_test.go | 24 ++++++++-------- .../gateway_request_json_equivalence_test.go | 28 +++++++++---------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/backend/internal/service/gateway_request_json_bench_test.go b/backend/internal/service/gateway_request_json_bench_test.go index 3ba89900f8..d56064a09c 100644 --- a/backend/internal/service/gateway_request_json_bench_test.go +++ b/backend/internal/service/gateway_request_json_bench_test.go @@ -11,27 +11,27 @@ import ( // 20 tools, a system prompt, and 40 messages with 4 content blocks each. func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { var b strings.Builder - b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`) + _, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`) for i := 0; i < 20; i++ { if i > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } fmt.Fprintf(&b, `{"name":"tool_%d","description":"%s","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}`, i, strings.Repeat("d", 40)) if i == 19 && cacheControls > 0 { - b.WriteString(`,"cache_control":{"type":"ephemeral"}`) + _, _ = b.WriteString(`,"cache_control":{"type":"ephemeral"}`) cacheControls-- } - b.WriteByte('}') + _ = b.WriteByte('}') } - b.WriteString(`],"system":[{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."`) + _, _ = b.WriteString(`],"system":[{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."`) if cacheControls > 0 { - b.WriteString(`,"cache_control":{"type":"ephemeral"}`) + _, _ = b.WriteString(`,"cache_control":{"type":"ephemeral"}`) cacheControls-- } - b.WriteString(`}],"messages":[`) + _, _ = b.WriteString(`}],"messages":[`) for m := 0; m < 40; m++ { if m > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } role := "user" if m%2 == 1 { @@ -40,7 +40,7 @@ func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { fmt.Fprintf(&b, `{"role":%q,"content":[`, role) for c := 0; c < 4; c++ { if c > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } fmt.Fprintf(&b, `{"type":"text","text":"%s"`, strings.Repeat("x", 120)) if m >= 38 && c == 3 && cacheControls > 0 { @@ -51,11 +51,11 @@ func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { fmt.Fprintf(&b, `,"cache_control":{"type":"ephemeral"%s}`, ttl) cacheControls-- } - b.WriteByte('}') + _ = b.WriteByte('}') } - b.WriteString(`]}`) + _, _ = b.WriteString(`]}`) } - b.WriteString(`]}`) + _, _ = b.WriteString(`]}`) return []byte(b.String()) } diff --git a/backend/internal/service/gateway_request_json_equivalence_test.go b/backend/internal/service/gateway_request_json_equivalence_test.go index 1d78c15c0e..e8fc31be32 100644 --- a/backend/internal/service/gateway_request_json_equivalence_test.go +++ b/backend/internal/service/gateway_request_json_equivalence_test.go @@ -145,43 +145,43 @@ func randomCacheControlBody(rng *rand.Rand) []byte { } } var b bytes.Buffer - b.WriteString(`{"model":"claude-sonnet"`) + _, _ = b.WriteString(`{"model":"claude-sonnet"`) if rng.Intn(5) == 0 { - b.WriteString(`,"cache_control":{"type":"ephemeral","ttl":"1h"}`) + _, _ = b.WriteString(`,"cache_control":{"type":"ephemeral","ttl":"1h"}`) } if rng.Intn(2) == 0 { - b.WriteString(`,"tools":[`) + _, _ = b.WriteString(`,"tools":[`) n := rng.Intn(4) for i := 0; i < n; i++ { if i > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } fmt.Fprintf(&b, `{"name":"tool_%d"%s}`, i, cc()) } - b.WriteByte(']') + _ = b.WriteByte(']') } if rng.Intn(2) == 0 { - b.WriteString(`,"system":[`) + _, _ = b.WriteString(`,"system":[`) n := rng.Intn(3) for i := 0; i < n; i++ { if i > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } fmt.Fprintf(&b, `{"type":"text","text":"sys %d"%s}`, i, cc()) } - b.WriteByte(']') + _ = b.WriteByte(']') } - b.WriteString(`,"messages":[`) + _, _ = b.WriteString(`,"messages":[`) m := rng.Intn(4) for i := 0; i < m; i++ { if i > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } - b.WriteString(`{"role":"user","content":[`) + _, _ = b.WriteString(`{"role":"user","content":[`) c := rng.Intn(3) + 1 for j := 0; j < c; j++ { if j > 0 { - b.WriteByte(',') + _ = b.WriteByte(',') } blockType := "text" if rng.Intn(6) == 0 { @@ -189,9 +189,9 @@ func randomCacheControlBody(rng *rand.Rand) []byte { } fmt.Fprintf(&b, `{"type":%q,"text":"m%d-%d"%s}`, blockType, i, j, cc()) } - b.WriteString(`]}`) + _, _ = b.WriteString(`]}`) } - b.WriteString(`]}`) + _, _ = b.WriteString(`]}`) return b.Bytes() } From e055d7bafc5b7eda444e0ec7c7aed99e2c802de1 Mon Sep 17 00:00:00 2001 From: Long Li Date: Wed, 11 Nov 2026 16:38:33 +0900 Subject: [PATCH 10/85] fix(antigravity): stream Gemini compat thoughts and anchor pre-content timeout after headers --- .../service/antigravity_gateway_compat.go | 3 +- .../antigravity_gateway_compat_stream.go | 77 ++++++- .../antigravity_gateway_compat_test.go | 206 ++++++++++++++++++ .../antigravity_gemini_thinking_variant.go | 16 ++ 4 files changed, 294 insertions(+), 8 deletions(-) diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index f1ebe19666..e27a11ce6d 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -259,7 +259,7 @@ func (s *AntigravityGatewayService) prepareAntigravityCompatCall( mappedModel := s.getMappedModelForThinkingLevel( account, request.originalModel, - geminiThinkingLevelFromClaudeThinking(claudeRequest.Thinking), + geminiThinkingLevelFromClaudeBody(request.claudeBody, claudeRequest.Thinking), ) if mappedModel == "" { MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate) @@ -322,6 +322,7 @@ func (s *AntigravityGatewayService) buildAntigravityCompatGeminiBody( return nil, err } body = ensureGeminiFunctionCallThoughtSignatures(body) + body = applyGeminiCompatThinkingConfig(body, claudeBody, mappedModel, claudeRequest != nil && claudeRequest.Stream) body, err = injectIdentityPatchToGeminiRequest(body) if err != nil { return nil, err diff --git a/backend/internal/service/antigravity_gateway_compat_stream.go b/backend/internal/service/antigravity_gateway_compat_stream.go index 4dea4c453c..33e4ece3ed 100644 --- a/backend/internal/service/antigravity_gateway_compat_stream.go +++ b/backend/internal/service/antigravity_gateway_compat_stream.go @@ -154,9 +154,9 @@ func (s *antigravityCompatStreamSession) hasMeaningfulData() bool { } func (s *antigravityCompatStreamSession) writePreContentKeepalive(now time.Time) { - // Intentional tradeoff: this commits HTTP 200 after 15s, so later upstream + // Intentional tradeoff: this commits HTTP 200 after the keepalive interval, so later upstream // failures cannot fail over; report them as SSE errors to the client instead. - if s.hasMeaningfulData() || s.writer.Disconnected() || now.Sub(s.startTime) < s.preContentKeepaliveInterval { + if s.hasMeaningfulData() || s.writer.Disconnected() || (!s.preContentKeepaliveSent && now.Sub(s.startTime) < s.preContentKeepaliveInterval) { return } if s.writer.Write([]byte(": ping\n\n")) { @@ -282,12 +282,52 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStream( adapter antigravityCompatStreamAdapter, prefix string, ) (*antigravityStreamResult, error) { - return s.handleAntigravityCompatStreamWithKeepaliveInterval(c, resp, startTime, originalModel, adapter, prefix, antigravityCompatPreContentKeepaliveInterval, antigravityCompatPreContentMaxWait) + return s.handleAntigravityCompatStreamWithKeepaliveInterval( + c, + resp, + startTime, + originalModel, + adapter, + prefix, + antigravityCompatPreContentKeepaliveInterval, + s.antigravityCompatPreContentMaxWait(), + ) +} + +// handleAntigravityCompatStreamAfterHeaders starts reading an upstream HTTP 200 SSE +// stream while keeping startTime for TTFT measurement and anchoring the pre-content +// deadline at response-header arrival rather than request start. +func (s *AntigravityGatewayService) handleAntigravityCompatStreamAfterHeaders( + c *gin.Context, + resp *http.Response, + startTime time.Time, + originalModel string, + adapter antigravityCompatStreamAdapter, + prefix string, +) (*antigravityStreamResult, error) { + return s.handleAntigravityCompatStreamWithTiming( + c, + resp, + startTime, + time.Now(), + originalModel, + adapter, + prefix, + s.antigravityCompatPreContentKeepaliveInterval(), + s.antigravityCompatPreContentMaxWait(), + ) } func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveInterval( c *gin.Context, resp *http.Response, startTime time.Time, originalModel string, adapter antigravityCompatStreamAdapter, prefix string, interval, maxPreContentWait time.Duration, +) (*antigravityStreamResult, error) { + return s.handleAntigravityCompatStreamWithTiming(c, resp, startTime, startTime, originalModel, adapter, prefix, interval, maxPreContentWait) +} + +func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithTiming( + c *gin.Context, resp *http.Response, startTime, streamStart time.Time, originalModel string, + adapter antigravityCompatStreamAdapter, prefix string, interval, maxPreContentWait time.Duration, ) (*antigravityStreamResult, error) { flusher, ok := c.Writer.(http.Flusher) if !ok { @@ -303,6 +343,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn c.Status(http.StatusOK) } session := newAntigravityCompatStreamSession(originalModel, startTime, adapter, writer) + session.preContentKeepaliveSent = IsResponseCommitted(c) && c.Writer.Written() session.preContentKeepaliveInterval = interval events, stopScanner, maxLineSize, queueBudget := s.startAntigravityCompatScanner(resp.Body) defer stopScanner() @@ -316,13 +357,17 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn if keepaliveTicker != nil { defer keepaliveTicker.Stop() } - preContentDelay := time.Until(startTime.Add(interval)) + keepaliveStart := startTime + if session.preContentKeepaliveSent { + keepaliveStart = streamStart + } + preContentDelay := time.Until(keepaliveStart.Add(interval)) if preContentDelay < 0 { preContentDelay = 0 } preContentTimer := time.NewTimer(preContentDelay) defer preContentTimer.Stop() - preContentDeadline := startTime.Add(maxPreContentWait) + preContentDeadline := streamStart.Add(maxPreContentWait) deadlineDelay := time.Until(preContentDeadline) if deadlineDelay < 0 { deadlineDelay = 0 @@ -447,6 +492,24 @@ func (s *AntigravityGatewayService) antigravityCompatStreamTimeout() time.Durati return time.Duration(s.settingService.cfg.Gateway.StreamDataIntervalTimeout) * time.Second } +func (s *AntigravityGatewayService) antigravityCompatPreContentKeepaliveInterval() time.Duration { + interval := antigravityCompatPreContentKeepaliveInterval + if s.settingService != nil && s.settingService.cfg != nil { + configured := time.Duration(s.settingService.cfg.Gateway.StreamKeepaliveInterval) * time.Second + if configured > 0 && configured < interval { + interval = configured + } + } + return interval +} + +func (s *AntigravityGatewayService) antigravityCompatPreContentMaxWait() time.Duration { + if timeout := s.antigravityCompatStreamTimeout(); timeout > antigravityCompatPreContentMaxWait { + return timeout + } + return antigravityCompatPreContentMaxWait +} + func (s *AntigravityGatewayService) newAntigravityCompatKeepaliveTicker() (*time.Ticker, <-chan time.Time) { if s.settingService == nil || s.settingService.cfg == nil { return nil, nil @@ -532,7 +595,7 @@ func (s *AntigravityGatewayService) handleChatCompletionsStreamingFromAntigravit originalModel string, includeUsage bool, ) (*antigravityStreamResult, error) { - return s.handleAntigravityCompatStream( + return s.handleAntigravityCompatStreamAfterHeaders( c, resp, startTime, @@ -548,7 +611,7 @@ func (s *AntigravityGatewayService) handleResponsesStreamingFromAntigravity( startTime time.Time, originalModel string, ) (*antigravityStreamResult, error) { - return s.handleAntigravityCompatStream( + return s.handleAntigravityCompatStreamAfterHeaders( c, resp, startTime, diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index bccbe2472f..b64cd78762 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -1256,3 +1256,209 @@ func TestAntigravityCompatEmptyAfterKeepaliveReportsStreamError(t *testing.T) { }) } } + +func TestAntigravityCompatGeminiThinkingConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("streaming responses tier suffix enables includeThoughts without thinkingLevel", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + body := []byte(`{"model":"gemini-4-argon-high","stream":true,"input":"inspect repository"}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body) + + _, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists(), "tier-suffixed model must not set thinkingLevel: %s", cfg.Raw) + require.False(t, cfg.Get("thinkingBudget").Exists(), "tier-suffixed model must not set thinkingBudget: %s", cfg.Raw) + }) + + t.Run("streaming chat completions tier suffix enables includeThoughts without thinkingLevel", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + body := []byte(`{"model":"gemini-4-argon-high","stream":true,"messages":[{"role":"user","content":"inspect repository"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists(), "thinkingConfig=%s", cfg.Raw) + }) + + t.Run("streaming responses bare model with low effort selects low variant and enables includeThoughts", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-low"] = "gemini-4-argon-low" + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + body := []byte(`{"model":"gemini-4-argon","stream":true,"reasoning":{"effort":"low"},"input":"quick check"}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body) + + result, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + require.Equal(t, "gemini-4-argon-low", gjson.GetBytes(upstream.requestBodies[0], "model").String()) + require.Equal(t, "gemini-4-argon-low", result.UpstreamModel) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists(), "thinkingConfig=%s", cfg.Raw) + }) + + t.Run("streaming responses explicit bare model sets thinkingLevel and includeThoughts", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-3.5-flash"] = "gemini-3.5-flash" + + body := []byte(`{"model":"gemini-3.5-flash","stream":true,"reasoning":{"effort":"medium"},"input":"check"}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body) + + _, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.Equal(t, "medium", cfg.Get("thinkingLevel").String(), "thinkingConfig=%s", cfg.Raw) + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + }) + + t.Run("non-streaming responses do not force includeThoughts", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + nonStreamBody := []byte(`{"model":"gemini-4-argon-high","stream":false,"input":"inspect"}`) + c, rec := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nonStreamBody) + _, err := svc.ForwardAsResponses(context.Background(), c, account, nonStreamBody, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Len(t, upstream.requestBodies, 1) + require.False(t, gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig.includeThoughts").Bool()) + }) +} + +func TestAntigravityCompatHeaderWaitExceedingPreContentLimitDoesNotAbortStream(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, protocol := range []antigravityCompatProtocol{antigravityCompatResponses, antigravityCompatChatCompletions} { + name := "responses" + path := "/v1/responses" + wantDone := "event: response.completed" + if protocol == antigravityCompatChatCompletions { + name = "chat_completions" + path = "/v1/chat/completions" + wantDone = "data: [DONE]" + } + for _, committedKeepalive := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/keepalive=%t", name, committedKeepalive), func(t *testing.T) { + svc := newAntigravityCompatService(config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, + StreamDataIntervalTimeout: 180, + StreamKeepaliveInterval: 10, + }, nil) + c, recorder := newAntigravityCompatContext(http.MethodPost, path, nil) + if committedKeepalive { + c.Header("Content-Type", "text/event-stream") + c.Status(http.StatusOK) + MarkResponseCommitted(c) + _, err := c.Writer.Write([]byte(": ping\n\n")) + require.NoError(t, err) + c.Writer.Flush() + } + + requestStart := time.Now().Add(-3 * time.Minute) + call := &antigravityCompatUpstreamCall{ + request: antigravityCompatRequest{ + protocol: protocol, + originalModel: "gemini-4-argon-high", + clientStream: true, + startTime: requestStart, + }, + billingModel: "gemini-4-argon-high", + prefix: "test-long-header-wait", + } + + result, err := svc.consumeAntigravityCompatResponse( + c.Request.Context(), + c, + newAntigravityCompatAccount(AccountTypeOAuth), + call, + antigravityCompatSuccessResponse(), + ) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.FirstTokenMs) + require.GreaterOrEqual(t, *result.FirstTokenMs, int((3*time.Minute - time.Second).Milliseconds())) + require.Contains(t, recorder.Body.String(), wantDone) + require.NotContains(t, recorder.Body.String(), "stream_timeout") + }) + } + } +} + +func TestAntigravityCompatInterleavedThoughtChunksResetIdleTimeout(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newAntigravityCompatService(config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, + StreamDataIntervalTimeout: 1, + }, nil) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nil) + reader, writer := io.Pipe() + defer func() { _ = reader.Close() }() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: reader, + } + + done := make(chan error, 1) + go func() { + _, err := svc.handleResponsesStreamingFromAntigravity(c, resp, time.Now(), "gemini-4-argon-high") + done <- err + }() + + _, err := io.WriteString(writer, `data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"text":"Checking files..."}]}}]}}`+"\n\n") + require.NoError(t, err) + for i := 0; i < 4; i++ { + time.Sleep(350 * time.Millisecond) + _, err = io.WriteString(writer, fmt.Sprintf(`data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"step %d "}]}}]}}`+"\n\n", i+1)) + require.NoError(t, err) + } + _, err = io.WriteString(writer, `data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_done","functionCall":{"name":"exec_command","args":{"cmd":"ls"},"id":"call_1"}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"thoughtsTokenCount":50}}}`+"\n\n") + require.NoError(t, err) + require.NoError(t, writer.Close()) + + require.NoError(t, <-done) + out := recorder.Body.String() + require.Contains(t, out, "event: response.reasoning_summary_text.delta") + require.Contains(t, out, "event: response.completed") + require.NotContains(t, out, "stream_timeout") +} diff --git a/backend/internal/service/antigravity_gemini_thinking_variant.go b/backend/internal/service/antigravity_gemini_thinking_variant.go index e0ebc5c470..63201ba1e2 100644 --- a/backend/internal/service/antigravity_gemini_thinking_variant.go +++ b/backend/internal/service/antigravity_gemini_thinking_variant.go @@ -85,6 +85,22 @@ func geminiThinkingLevelFromBody(body []byte) string { } } +// geminiThinkingLevelFromClaudeBody 结合兼容层转换后的 output_config.effort 与 thinking 配置推导档位。 +// OpenAI Responses / Chat Completions 在 effort=low/minimal/none 时可能只写 output_config.effort 而不写 thinking, +// 优先读取显式 effort 可避免裸 Gemini 模型被默认归入 high 变体。 +func geminiThinkingLevelFromClaudeBody(claudeBody []byte, thinking *antigravity.ThinkingConfig) string { + switch parseClaudeThinkingIntent(claudeBody).tier { + case "minimal", "low": + return "low" + case "medium": + return "medium" + case "high": + return "high" + default: + return geminiThinkingLevelFromClaudeThinking(thinking) + } +} + // geminiThinkingLevelFromClaudeThinking 用 Claude Messages 协议的 thinking 配置推导档位, // 阈值与 geminiThinkingLevelFromBody 保持一致,使同一请求无论走 Gemini 原生还是 // Chat Completions / Messages 兼容层都落到同一个上游变体。 From 23ac69a0219c77e29de7b8f4195a40ccc745a7b4 Mon Sep 17 00:00:00 2001 From: feeeei Date: Wed, 11 Nov 2026 15:50:11 +0800 Subject: [PATCH 11/85] =?UTF-8?q?fix(bedrock):=20=E6=8C=89=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E8=AF=AD=E4=B9=89=E5=8C=BA=E5=88=86=E5=B0=81=E5=8F=B7?= =?UTF-8?q?=E3=80=81=E7=94=A8=E4=BE=8B=E7=BC=BA=E5=A4=B1=E3=80=81=E9=99=90?= =?UTF-8?q?=E6=B5=81=E4=B8=8E=E5=86=85=E5=AE=B9=E8=BF=87=E6=BB=A4=EF=BC=8C?= =?UTF-8?q?=E6=B5=81=E4=B8=AD=E6=96=AD=E4=BF=9D=E7=95=99=20usage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 400 消息整句为 "Operation not allowed"(AWS 封号):账号置 error 并换号;其余 Bedrock 400 一律按请求错误处理,不按消息子串改账号状态(ValidationException 会把请求字段名回显进消息) - 404 "Model use case details have not been submitted..."(未提交模型用例):账号置 error 并换号 - 429 只冷却 (账号, 模型),时长取「429 默认回避」配置,配置关闭时不写;模型未知时沿用账号级兜底 - 500/502/503/504 且消息含 "blocked by content filtering policy":不换号、不惩罚账号,返回客户端 400 invalid_request_error 与上游原文 - 渠道模型映射生效时,handler 经 WithGatewaySchedulingModel 传入选号模型,模型级账号状态写在调度器按客户端模型读取的键上 - 流式输出中断时与错误一起返回已观测的 usage,照常计费 - 临时不可调度规则仍优先于以上默认分类 --- backend/internal/handler/gateway_handler.go | 4 + backend/internal/service/gateway_bedrock.go | 18 +- .../service/gateway_upstream_response.go | 7 + backend/internal/service/ratelimit_bedrock.go | 110 +++++ .../service/ratelimit_bedrock_test.go | 451 ++++++++++++++++++ backend/internal/service/ratelimit_service.go | 5 + 6 files changed, 592 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/ratelimit_bedrock.go create mode 100644 backend/internal/service/ratelimit_bedrock_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 6ec51d5430..154d7df318 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -915,6 +915,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if fs.ForceCacheBilling { requestCtx = service.WithForceCacheBilling(requestCtx) } + if channelMapping.Mapped { + // 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。 + requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel) + } // 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover writerSizeBeforeForward := c.Writer.Size() if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { diff --git a/backend/internal/service/gateway_bedrock.go b/backend/internal/service/gateway_bedrock.go index 60d6937fbb..196d977579 100644 --- a/backend/internal/service/gateway_bedrock.go +++ b/backend/internal/service/gateway_bedrock.go @@ -130,9 +130,7 @@ func (s *GatewayService) forwardBedrock( // 错误/failover 处理 if resp.StatusCode >= 400 { - // 账号状态按模型隔离时用调度器的模型键(账号映射后的模型名),不是发往上游的 Bedrock 模型 ID; - // 两者不一致会让模型级冷却写到调度器不会读取的键上。 - return s.handleBedrockUpstreamErrors(ctx, resp, c, account, account.GetMappedModel(reqModel)) + return s.handleBedrockUpstreamErrors(ctx, resp, c, account, bedrockSchedulingModelKey(ctx, account, reqModel)) } // Bedrock 分支绕过通用 Forward 成功路径,这里保持上游接受回调语义一致。 @@ -147,6 +145,10 @@ func (s *GatewayService) forwardBedrock( if reqStream { streamResult, err := s.handleBedrockStreamingResponse(ctx, resp, c, account, startTime, reqModel) if err != nil { + // 流中断时保留已观测到的 usage 与错误一起返回,handler 照常提交 usage 记录。 + if partial := partialStreamUsageResult(c, resp, streamResult, reqModel, mappedModel, startTime, err); partial != nil { + return partial, err + } return nil, err } usage = streamResult.usage @@ -274,6 +276,16 @@ func (s *GatewayService) handleBedrockUpstreamErrors( account *Account, modelKey string, ) (*ForwardResult, error) { + // 内容过滤由请求内容决定,换号结果相同:不换号,按普通错误返回客户端。 + if resp.StatusCode >= http.StatusInternalServerError { + respBody, _ := s.readUpstreamErrorBody(resp) + _ = resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(respBody)) + if isBedrockContentFilterError(resp.StatusCode, respBody) { + return s.handleErrorResponse(ctx, resp, c, account, modelKey) + } + } + // retry exhausted + failover if s.shouldRetryUpstreamError(account, resp.StatusCode) { if s.shouldFailoverUpstreamError(resp.StatusCode) { diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 85b415e5cf..0a44997b26 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -503,6 +503,13 @@ func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Res errType = "overloaded_error" errMsg = "Upstream service overloaded, please retry later" case 500, 502, 503, 504: + // Bedrock 内容过滤是请求级的确定性结果,按请求错误返回,客户端不应原样重试。 + if account.IsBedrock() && isBedrockContentFilterError(resp.StatusCode, body) && upstreamMsg != "" { + statusCode = http.StatusBadRequest + errType = "invalid_request_error" + errMsg = upstreamMsg + break + } statusCode = http.StatusBadGateway errType = "upstream_error" errMsg = "Upstream service temporarily unavailable" diff --git a/backend/internal/service/ratelimit_bedrock.go b/backend/internal/service/ratelimit_bedrock.go new file mode 100644 index 0000000000..a3f29a14e5 --- /dev/null +++ b/backend/internal/service/ratelimit_bedrock.go @@ -0,0 +1,110 @@ +package service + +import ( + "context" + "log/slog" + "net/http" + "strings" + "time" +) + +// Bedrock 错误文案(小写,与 extractUpstreamErrorMessage 的结果比对)。 +// 400 ValidationException 会把请求里的非法字段名回显进消息,账号级判定只认整句或固定开头, +// 不按子串匹配,避免请求内容触发停号。 +const ( + // 400 ValidationException:AWS 封禁账号后所有调用返回的完整消息。 + bedrockAccountBlockedMessage = "operation not allowed" + // 404 ResourceNotFoundException:账号未提交 Anthropic 模型用例表单时消息的开头。 + bedrockUseCaseMissingPrefix = "model use case details have not been submitted" + // 5xx:Bedrock 内容过滤拦截了请求或输出。 + bedrockContentFilterMarker = "blocked by content filtering policy" + + bedrockThrottlingReason = "bedrock_throttling" +) + +type gatewaySchedulingModelContextKey struct{} + +// WithGatewaySchedulingModel 记录选号时使用的客户端模型。请求经渠道模型映射改写模型后转发时, +// Bedrock 账号的模型级状态按该模型推导调度器读取的键。 +func WithGatewaySchedulingModel(ctx context.Context, model string) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, gatewaySchedulingModelContextKey{}, strings.TrimSpace(model)) +} + +// bedrockSchedulingModelKey 返回调度器按模型隔离账号状态时读取的键:账号映射后的选号模型; +// 上下文未记录选号模型时用本次转发的模型。键不是发往上游的 Bedrock 模型 ID。 +func bedrockSchedulingModelKey(ctx context.Context, account *Account, forwardModel string) string { + model := forwardModel + if ctx != nil { + if scheduling, _ := ctx.Value(gatewaySchedulingModelContextKey{}).(string); scheduling != "" { + model = scheduling + } + } + return account.GetMappedModel(model) +} + +// handleBedrockUpstreamError 处理 Bedrock 账号特有的错误语义,handled=false 时交回通用逻辑。 +// +// Bedrock 的限流额度按(AWS 账号、源区域、推理配置、模型)计算,而一个 Bedrock 账号固定了 +// AWS 凭证、区域与推理配置,所以 429 只冷却本次请求的模型;模型未知时交回通用的账号级兜底。 +func (s *RateLimitService) handleBedrockUpstreamError(ctx context.Context, account *Account, statusCode int, upstreamMsg string, modelKey string) (handled bool, shouldDisable bool) { + switch statusCode { + case http.StatusBadRequest: + if isBedrockAccountBlockedMessage(upstreamMsg) { + s.handleAuthError(ctx, account, "Bedrock account blocked (400): "+upstreamMsg) + return true, true + } + // 其余 400 都是请求错误,不影响账号状态。 + return true, false + case http.StatusNotFound: + if strings.HasPrefix(normalizeBedrockErrorMessage(upstreamMsg), bedrockUseCaseMissingPrefix) { + s.handleAuthError(ctx, account, "Bedrock model use case not submitted (404): "+upstreamMsg) + return true, true + } + case http.StatusTooManyRequests: + modelKey = strings.TrimSpace(modelKey) + if modelKey == "" { + return false, false + } + s.applyBedrockModelThrottle(ctx, account, modelKey) + return true, false + } + return false, false +} + +// applyBedrockModelThrottle 按 429 默认回避配置冷却 (账号, 模型);回避关闭时不写任何状态。 +func (s *RateLimitService) applyBedrockModelThrottle(ctx context.Context, account *Account, modelKey string) { + cooldown, enabled := s.get429FallbackCooldown(ctx, account) + if !enabled { + slog.Info("bedrock_throttling_cooldown_ignored", "account_id", account.ID, "model", modelKey) + return + } + resetAt := time.Now().Add(cooldown) + if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, resetAt, bedrockThrottlingReason); err != nil { + slog.Warn("bedrock_throttling_set_model_rate_limit_failed", "account_id", account.ID, "model", modelKey, "error", err) + return + } + slog.Info("bedrock_throttling_model_rate_limited", "account_id", account.ID, "model", modelKey, "reset_at", resetAt) +} + +func normalizeBedrockErrorMessage(msg string) string { + return strings.ToLower(strings.TrimSpace(msg)) +} + +// isBedrockAccountBlockedMessage 按整句比对封号消息(忽略大小写与句末句点)。 +func isBedrockAccountBlockedMessage(msg string) bool { + return strings.TrimSuffix(normalizeBedrockErrorMessage(msg), ".") == bedrockAccountBlockedMessage +} + +// isBedrockContentFilterError 判断上游错误是否为 Bedrock 内容过滤拦截;状态码集合与 +// handleErrorResponse 把 5xx 改写为客户端响应的 case 一致(500/502/503/504)。 +func isBedrockContentFilterError(statusCode int, body []byte) bool { + switch statusCode { + case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + default: + return false + } + return strings.Contains(normalizeBedrockErrorMessage(extractUpstreamErrorMessage(body)), bedrockContentFilterMarker) +} diff --git a/backend/internal/service/ratelimit_bedrock_test.go b/backend/internal/service/ratelimit_bedrock_test.go new file mode 100644 index 0000000000..297ab023b2 --- /dev/null +++ b/backend/internal/service/ratelimit_bedrock_test.go @@ -0,0 +1,451 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "errors" + "hash/crc32" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type bedrockErrorRepoStub struct { + tempUnschedScopeRepoStub + errorMessages []string + rateLimitedAt []time.Time +} + +func (r *bedrockErrorRepoStub) SetError(_ context.Context, _ int64, msg string) error { + r.errorCalls++ + r.errorMessages = append(r.errorMessages, msg) + return nil +} + +func (r *bedrockErrorRepoStub) SetRateLimited(_ context.Context, _ int64, resetAt time.Time) error { + r.rateLimitedAt = append(r.rateLimitedAt, resetAt) + return nil +} + +type bedrockErrorUpstreamStub struct { + status int + header http.Header + body []byte + calls int + lastURL string +} + +func (u *bedrockErrorUpstreamStub) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + return u.DoWithTLS(req, proxyURL, accountID, accountConcurrency, nil) +} + +func (u *bedrockErrorUpstreamStub) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + u.calls++ + u.lastURL = req.URL.String() + header := http.Header{"Content-Type": []string{"application/json"}, "X-Amzn-Requestid": []string{"aws-req-1"}} + for k, v := range u.header { + header[k] = v + } + return &http.Response{StatusCode: u.status, Header: header, Body: io.NopCloser(bytes.NewReader(u.body))}, nil +} + +func newBedrockErrorTestAccount(rules ...map[string]any) *Account { + account := &Account{ + ID: 77, + Name: "bedrock-error-test", + Platform: PlatformAnthropic, + Type: AccountTypeBedrock, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "auth_mode": "apikey", + "api_key": "bedrock-key", + "aws_region": "us-east-1", + }, + } + if len(rules) > 0 { + raw := make([]any, 0, len(rules)) + for _, rule := range rules { + raw = append(raw, rule) + } + account.Credentials["temp_unschedulable_enabled"] = true + account.Credentials["temp_unschedulable_rules"] = raw + } + return account +} + +type bedrockForwardOutcome struct { + result *ForwardResult + err error + failover *UpstreamFailoverError + recorder *httptest.ResponseRecorder + upstream *bedrockErrorUpstreamStub +} + +type bedrockForwardOptions struct { + ctx context.Context + model string + stream bool + rateLimiter *RateLimitService +} + +func runBedrockForward(t *testing.T, repo *bedrockErrorRepoStub, account *Account, upstream *bedrockErrorUpstreamStub, stream bool) bedrockForwardOutcome { + t.Helper() + return runBedrockForwardWith(t, repo, account, upstream, bedrockForwardOptions{stream: stream}) +} + +func runBedrockForwardWith(t *testing.T, repo *bedrockErrorRepoStub, account *Account, upstream *bedrockErrorUpstreamStub, opts bedrockForwardOptions) bedrockForwardOutcome { + t.Helper() + gin.SetMode(gin.TestMode) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}} + rateLimiter := opts.rateLimiter + if rateLimiter == nil { + rateLimiter = &RateLimitService{accountRepo: repo, cfg: cfg} + } + ctx := opts.ctx + if ctx == nil { + ctx = context.Background() + } + model := opts.model + if model == "" { + model = "claude-sonnet-4-5" + } + svc := &GatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: rateLimiter} + body := []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: model, Stream: opts.stream} + + result, err := svc.forwardBedrock(ctx, c, account, parsed, time.Now()) + out := bedrockForwardOutcome{result: result, err: err, recorder: rec, upstream: upstream} + var failover *UpstreamFailoverError + if errors.As(err, &failover) { + out.failover = failover + } + return out +} + +func bedrockErrorRule(statusCode int, keyword string, minutes int, scope string) map[string]any { + return map[string]any{ + "error_code": float64(statusCode), + "keywords": []any{keyword}, + "duration_minutes": float64(minutes), + "scope": scope, + } +} + +func TestBedrockUpstreamErrors_AccountBlockedDisablesAndFailsOver(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(`{"message":"Operation not allowed"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, "封号必须换号,不能把 400 回给客户端") + require.Equal(t, http.StatusBadRequest, out.failover.StatusCode) + require.Equal(t, 1, repo.errorCalls) + require.Contains(t, repo.errorMessages[0], "Operation not allowed") + require.Zero(t, out.recorder.Body.Len()) +} + +func TestBedrockUpstreamErrors_UseCaseMissingDisablesAndFailsOver(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusNotFound, body: []byte(`{"message":"Model use case details have not been submitted for this account. Fill out the Anthropic use case details form before using the model. If you have already filled out the form, try again in 15 minutes."}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover) + require.Equal(t, http.StatusNotFound, out.failover.StatusCode) + require.Equal(t, 1, repo.errorCalls) + require.Empty(t, repo.modelRateLimitCalls, "用例未提交是账号级问题,不按模型不存在冷却") + require.Zero(t, out.recorder.Body.Len()) +} + +func TestBedrockUpstreamErrors_TempUnschedRuleOverridesAccountLevelDefaults(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusNotFound, body: []byte(`{"message":"Model use case details have not been submitted for this account."}`)} + account := newBedrockErrorTestAccount(bedrockErrorRule(http.StatusNotFound, "use case details", 30, TempUnschedScopeAccount)) + + out := runBedrockForward(t, repo, account, upstream, false) + + require.NotNil(t, out.failover) + require.Zero(t, repo.errorCalls) + require.Equal(t, 1, repo.tempCalls) +} + +func TestBedrockUpstreamErrors_ThrottlingCoolsOnlyRequestedModel(t *testing.T) { + for _, msg := range []string{ + "Too many requests, please wait before trying again.", + "Too many tokens per day, please wait before trying again.", + } { + t.Run(msg, func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"` + msg + `"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover) + require.Equal(t, http.StatusTooManyRequests, out.failover.StatusCode) + require.Equal(t, 1, upstream.calls, "Bedrock 429 不在同一个桶上重试") + require.Empty(t, repo.rateLimitedAt, "429 不冷却整个账号") + require.Len(t, repo.modelRateLimitCalls, 1) + call := repo.modelRateLimitCalls[0] + require.Equal(t, "claude-sonnet-4-5", call.scope, "冷却键与调度器读取的模型键一致") + require.Equal(t, bedrockThrottlingReason, call.reason) + require.WithinDuration(t, time.Now().Add(defaultRateLimit429CooldownSeconds*time.Second), call.resetAt, 2*time.Second) + }) + } +} + +func TestBedrockUpstreamErrors_DailyTokenRuleTakesPrecedenceOverThrottlingCooldown(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many tokens per day, please wait before trying again."}`)} + account := newBedrockErrorTestAccount(bedrockErrorRule(http.StatusTooManyRequests, "tokens per day", 240, TempUnschedScopeModel)) + + out := runBedrockForward(t, repo, account, upstream, false) + + require.NotNil(t, out.failover) + require.Empty(t, repo.rateLimitedAt) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope) + require.WithinDuration(t, time.Now().Add(240*time.Minute), repo.modelRateLimitCalls[0].resetAt, 2*time.Second) +} + +func TestBedrockThrottlingWithoutModelFallsBackToAccountCooldown(t *testing.T) { + repo := &bedrockErrorRepoStub{} + svc := &RateLimitService{accountRepo: repo} + + shouldDisable := svc.HandleUpstreamError(context.Background(), newBedrockErrorTestAccount(), http.StatusTooManyRequests, http.Header{}, []byte(`{"message":"Too many requests, please wait before trying again."}`)) + + require.False(t, shouldDisable) + require.Empty(t, repo.modelRateLimitCalls) + require.Len(t, repo.rateLimitedAt, 1) +} + +func TestBedrockUpstreamErrors_ContentFilterReturnsRequestErrorWithoutFailover(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusInternalServerError, body: []byte(`{"message":"Output blocked by content filtering policy"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Error(t, out.err) + require.Nil(t, out.failover, "内容过滤换号结果相同,不换号") + require.Equal(t, http.StatusBadRequest, out.recorder.Code) + require.Equal(t, "invalid_request_error", gjson.Get(out.recorder.Body.String(), "error.type").String()) + require.Equal(t, "Output blocked by content filtering policy", gjson.Get(out.recorder.Body.String(), "error.message").String()) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + require.Empty(t, repo.rateLimitedAt) +} + +func TestBedrockUpstreamErrors_ServerErrorsStillFailOverWithoutPenalty(t *testing.T) { + for _, tc := range []struct { + status int + body string + }{ + {http.StatusInternalServerError, `{"message":"Internal server error"}`}, + {http.StatusServiceUnavailable, `{"message":"Bedrock is unable to process your request."}`}, + } { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: tc.status, body: []byte(tc.body)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, "status %d", tc.status) + require.Equal(t, tc.status, out.failover.StatusCode) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + require.Empty(t, repo.rateLimitedAt) + } +} + +func TestBedrockUpstreamErrors_OtherValidationErrorsReturnToClient(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(`{"message":"messages.0.content.0.image.source.base64: image exceeds 5 MB maximum"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Error(t, out.err) + require.Nil(t, out.failover) + require.Equal(t, http.StatusBadRequest, out.recorder.Code) + require.Zero(t, repo.errorCalls) +} + +func buildBedrockEventStreamFrame(headers map[string]string, payload []byte) []byte { + var headersBuf bytes.Buffer + for _, name := range []string{":event-type", ":exception-type", ":message-type"} { + value, ok := headers[name] + if !ok { + continue + } + _ = headersBuf.WriteByte(byte(len(name))) + _, _ = headersBuf.WriteString(name) + _ = headersBuf.WriteByte(7) + _ = binary.Write(&headersBuf, binary.BigEndian, uint16(len(value))) + _, _ = headersBuf.WriteString(value) + } + headerBytes := headersBuf.Bytes() + total := uint32(12 + len(headerBytes) + len(payload) + 4) + + var prelude bytes.Buffer + _ = binary.Write(&prelude, binary.BigEndian, total) + _ = binary.Write(&prelude, binary.BigEndian, uint32(len(headerBytes))) + + var frame bytes.Buffer + _, _ = frame.Write(prelude.Bytes()) + _ = binary.Write(&frame, binary.BigEndian, crc32.ChecksumIEEE(prelude.Bytes())) + _, _ = frame.Write(headerBytes) + _, _ = frame.Write(payload) + _ = binary.Write(&frame, binary.BigEndian, crc32.ChecksumIEEE(frame.Bytes())) + return frame.Bytes() +} + +func bedrockChunkFrame(event string) []byte { + payload := []byte(`{"bytes":"` + base64.StdEncoding.EncodeToString([]byte(event)) + `"}`) + return buildBedrockEventStreamFrame(map[string]string{":event-type": "chunk", ":message-type": "event"}, payload) +} + +func TestForwardBedrockStreamInterruptionKeepsObservedUsage(t *testing.T) { + var stream bytes.Buffer + _, _ = stream.Write(bedrockChunkFrame(`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","usage":{"input_tokens":120,"cache_read_input_tokens":30,"output_tokens":1}}}`)) + _, _ = stream.Write(bedrockChunkFrame(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hel"}}`)) + _, _ = stream.Write(buildBedrockEventStreamFrame(map[string]string{ + ":exception-type": "internalServerException", + ":message-type": "exception", + }, []byte(`{"message":"Overloaded"}`))) + + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{ + status: http.StatusOK, + header: http.Header{"Content-Type": []string{"application/vnd.amazon.eventstream"}}, + body: stream.Bytes(), + } + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, true) + + require.Error(t, out.err) + require.Nil(t, out.failover, "已向客户端输出内容后不换号") + require.Contains(t, out.err.Error(), "internalServerException") + require.NotNil(t, out.result, "流中断时返回已观测到的 usage 供计费") + require.Equal(t, 120, out.result.Usage.InputTokens) + require.Equal(t, 30, out.result.Usage.CacheReadInputTokens) + require.Equal(t, "claude-sonnet-4-5", out.result.Model) + require.True(t, strings.HasPrefix(out.result.UpstreamModel, "us.anthropic.claude-sonnet-4-5"), out.result.UpstreamModel) + require.Equal(t, "aws-req-1", out.result.RequestID) + require.True(t, out.result.Stream) + require.Contains(t, out.recorder.Body.String(), "message_start") +} + +func TestBedrockUpstreamErrors_AccountBlockedMatchesWholeMessageOnly(t *testing.T) { + for _, msg := range []string{"Operation not allowed", "operation not allowed.", " OPERATION NOT ALLOWED "} { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(`{"message":"` + msg + `"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, msg) + require.Equal(t, 1, repo.errorCalls, msg) + } +} + +func TestBedrockUpstreamErrors_EchoedRequestContentDoesNotDisableAccount(t *testing.T) { + for _, echoed := range []string{"Operation not allowed", "credit balance", "organization has been disabled", "identity verification is required"} { + t.Run(echoed, func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + body := `{"message":"Malformed input request: #: extraneous key [` + echoed + `] is not permitted, please reformat your input and try again."}` + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(body)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Nil(t, out.failover, "请求错误不换号") + require.Equal(t, http.StatusBadRequest, out.recorder.Code) + require.Zero(t, repo.errorCalls, "回显进错误消息的请求内容不能触发停号") + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + }) + } +} + +func TestBedrockUpstreamErrors_ChannelMappedModelCoolsSchedulingKey(t *testing.T) { + ctx := WithGatewaySchedulingModel(context.Background(), "claude-sonnet-4-5") + + t.Run("throttling", func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many requests, please wait before trying again."}`)} + account := newBedrockErrorTestAccount() + + out := runBedrockForwardWith(t, repo, account, upstream, bedrockForwardOptions{ctx: ctx, model: "claude-sonnet-4-6"}) + + require.NotNil(t, out.failover) + require.Contains(t, upstream.lastURL, "claude-sonnet-4-6", "上游按渠道映射后的模型请求") + require.Len(t, repo.modelRateLimitCalls, 1) + scope := repo.modelRateLimitCalls[0].scope + require.Equal(t, "claude-sonnet-4-5", scope, "冷却写在调度器按客户端模型读取的键上") + setAccountModelRateLimitSnapshot(account, scope, time.Now().Add(time.Minute), bedrockThrottlingReason, time.Now()) + require.False(t, account.IsSchedulableForModelWithContext(context.Background(), "claude-sonnet-4-5")) + }) + + t.Run("model scoped rule", func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many tokens per day, please wait before trying again."}`)} + account := newBedrockErrorTestAccount(bedrockErrorRule(http.StatusTooManyRequests, "tokens per day", 240, TempUnschedScopeModel)) + + out := runBedrockForwardWith(t, repo, account, upstream, bedrockForwardOptions{ctx: ctx, model: "claude-sonnet-4-6"}) + + require.NotNil(t, out.failover) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope) + }) +} + +func TestBedrockUpstreamErrors_ThrottlingCooldownDisabledWritesNothing(t *testing.T) { + repo := &bedrockErrorRepoStub{} + settingRepo := newMockSettingRepo() + settingRepo.data[SettingKeyRateLimit429CooldownSettings] = `{"enabled":false,"cooldown_seconds":12}` + rateLimiter := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rateLimiter.SetSettingService(NewSettingService(settingRepo, &config.Config{})) + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many requests, please wait before trying again."}`)} + + out := runBedrockForwardWith(t, repo, newBedrockErrorTestAccount(), upstream, bedrockForwardOptions{rateLimiter: rateLimiter}) + + require.NotNil(t, out.failover) + require.Empty(t, repo.modelRateLimitCalls) + require.Empty(t, repo.rateLimitedAt) +} + +func TestBedrockUpstreamErrors_ContentFilterOnlyForRewrittenServerErrors(t *testing.T) { + for _, status := range []int{501, 529} { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: status, body: []byte(`{"message":"Output blocked by content filtering policy"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, "status %d 按原有 5xx 语义换号", status) + require.Equal(t, status, out.failover.StatusCode) + } + for _, status := range []int{500, 502, 503, 504} { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: status, body: []byte(`{"message":"Input blocked by content filtering policy"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Nil(t, out.failover, "status %d", status) + require.Equal(t, http.StatusBadRequest, out.recorder.Code, "status %d", status) + } +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 61c065ec0d..e0ec3476fe 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -424,6 +424,11 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc return false } } + if account.IsBedrock() { + if handled, disable := s.handleBedrockUpstreamError(ctx, account, statusCode, upstreamMsg, firstRequestedModel(requestedModel)); handled { + return disable + } + } switch statusCode { case 400: From fe40612b804dc848be85fcf677bb4e23824918d8 Mon Sep 17 00:00:00 2001 From: Shilin Zhou Date: Wed, 11 Nov 2026 17:46:45 +0800 Subject: [PATCH 12/85] fix: allow disabling concurrency wait pings --- backend/internal/config/config.go | 6 +- backend/internal/config/config_test.go | 26 +++---- backend/internal/handler/gateway_handler.go | 2 +- backend/internal/handler/gateway_helper.go | 4 +- .../handler/gateway_helper_ping_test.go | 67 +++++++++++++++++++ .../handler/openai_gateway_handler.go | 2 +- .../internal/handler/user_msg_queue_helper.go | 6 +- deploy/config.example.yaml | 4 +- 8 files changed, 93 insertions(+), 24 deletions(-) create mode 100644 backend/internal/handler/gateway_helper_ping_test.go diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index baf3260dc9..3e264053d3 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1025,7 +1025,7 @@ type CircuitBreakerConfig struct { } type ConcurrencyConfig struct { - // PingInterval: 并发等待期间的 SSE ping 间隔(秒) + // PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping PingInterval int `mapstructure:"ping_interval"` } @@ -3887,8 +3887,8 @@ func (c *Config) Validate() error { if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" { return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true") } - if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 { - return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds") + if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) { + return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds") } if c.Gateway.Grok.FreeQuotaSoftGateEnabled { if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 { diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 33a8f13d86..9c17de959b 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -1577,18 +1577,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) { func TestValidateConcurrencyPingInterval(t *testing.T) { resetViperWithJWTSecret(t) - - cfg, err := Load() - if err != nil { - t.Fatalf("Load() error: %v", err) - } - cfg.Concurrency.PingInterval = 3 - err = cfg.Validate() - if err == nil { - t.Fatalf("Validate() expected error for concurrency.ping_interval") - } - if !strings.Contains(err.Error(), "concurrency.ping_interval") { - t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err) + for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} { + cfg, err := Load() + if err != nil { + t.Fatalf("Load() error: %v", err) + } + cfg.Concurrency.PingInterval = interval + err = cfg.Validate() + valid := interval == 0 || (interval >= 5 && interval <= 30) + if valid && err != nil { + t.Errorf("Validate() interval %d: %v", interval, err) + } + if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) { + t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err) + } } } diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 6ec51d5430..d464b4afa5 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -80,7 +80,7 @@ func NewGatewayHandler( cfg *config.Config, settingService *service.SettingService, ) *GatewayHandler { - pingInterval := time.Duration(0) + pingInterval := defaultPingInterval maxAccountSwitches := 10 maxAccountSwitchesGemini := 3 if cfg != nil { diff --git a/backend/internal/handler/gateway_helper.go b/backend/internal/handler/gateway_helper.go index 02c275e2b0..8fdf726f10 100644 --- a/backend/internal/handler/gateway_helper.go +++ b/backend/internal/handler/gateway_helper.go @@ -172,7 +172,7 @@ type ConcurrencyHelper struct { // NewConcurrencyHelper creates a new ConcurrencyHelper func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFormat SSEPingFormat, pingInterval time.Duration) *ConcurrencyHelper { - if pingInterval <= 0 { + if pingInterval < 0 { pingInterval = defaultPingInterval } return &ConcurrencyHelper{ @@ -380,7 +380,7 @@ func (h *ConcurrencyHelper) waitForSlotWithPingTimeout(c *gin.Context, slotType } // Determine if ping is needed (streaming + ping format defined) - needPing := isStream && h.pingFormat != "" + needPing := isStream && h.pingFormat != "" && h.pingInterval > 0 var flusher http.Flusher if needPing { diff --git a/backend/internal/handler/gateway_helper_ping_test.go b/backend/internal/handler/gateway_helper_ping_test.go new file mode 100644 index 0000000000..051b8f357e --- /dev/null +++ b/backend/internal/handler/gateway_helper_ping_test.go @@ -0,0 +1,67 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestConcurrencyWaitPingInterval(t *testing.T) { + for _, slotType := range []string{"user", "account"} { + for _, format := range []SSEPingFormat{SSEPingFormatClaude, SSEPingFormatComment} { + for _, interval := range []time.Duration{0, time.Millisecond} { + t.Run(slotType+"/"+string(format)+"/"+interval.String(), func(t *testing.T) { + cache := &helperConcurrencyCacheStub{} + helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), format, interval) + require.Equal(t, interval, helper.pingInterval) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + started := false + _, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, 150*time.Millisecond, true, &started, false) + var concurrencyErr *ConcurrencyError + require.ErrorAs(t, err, &concurrencyErr) + require.True(t, concurrencyErr.IsTimeout) + if interval == 0 { + require.False(t, started) + require.False(t, c.Writer.Written()) + require.False(t, recorder.Flushed) + require.Empty(t, recorder.Body.String()) + require.Empty(t, recorder.Header().Get("Content-Type")) + c.JSON(http.StatusTooManyRequests, gin.H{"error": "busy"}) + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + } else { + require.True(t, started) + require.True(t, recorder.Flushed) + require.Contains(t, recorder.Body.String(), string(format)) + } + }) + } + } + } +} + +func TestConcurrencyWaitWithoutPingAcquiresSlot(t *testing.T) { + for _, slotType := range []string{"user", "account"} { + t.Run(slotType, func(t *testing.T) { + cache := &helperConcurrencyCacheStub{userSeq: []bool{true}, accountSeq: []bool{true}} + helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + started := false + release, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, time.Second, true, &started, false) + require.NoError(t, err) + require.NotNil(t, release) + release() + require.False(t, started) + require.False(t, c.Writer.Written()) + require.Empty(t, recorder.Body.String()) + }) + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index f70bce78b2..519f03ad31 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -364,7 +364,7 @@ func NewOpenAIGatewayHandler( opsService *service.OpsService, cfg *config.Config, ) *OpenAIGatewayHandler { - pingInterval := time.Duration(0) + pingInterval := defaultPingInterval maxAccountSwitches := 3 if cfg != nil { pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second diff --git a/backend/internal/handler/user_msg_queue_helper.go b/backend/internal/handler/user_msg_queue_helper.go index 839b14cbb6..831715495e 100644 --- a/backend/internal/handler/user_msg_queue_helper.go +++ b/backend/internal/handler/user_msg_queue_helper.go @@ -27,7 +27,7 @@ func NewUserMsgQueueHelper( pingFormat SSEPingFormat, pingInterval time.Duration, ) *UserMsgQueueHelper { - if pingInterval <= 0 { + if pingInterval < 0 { pingInterval = defaultPingInterval } return &UserMsgQueueHelper{ @@ -86,7 +86,7 @@ func (h *UserMsgQueueHelper) waitForLockWithPing( streamStarted *bool, reqLog *zap.Logger, ) (func(), error) { - needPing := isStream && h.pingFormat != "" + needPing := isStream && h.pingFormat != "" && h.pingInterval > 0 var flusher http.Flusher if needPing { @@ -196,7 +196,7 @@ func (h *UserMsgQueueHelper) ThrottleWithPing( ) // 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑) - needPing := isStream && h.pingFormat != "" + needPing := isStream && h.pingFormat != "" && h.pingInterval > 0 var flusher http.Flusher if needPing { flusher, _ = c.Writer.(http.Flusher) diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 2c6859ec0d..8bf3900a0e 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -882,8 +882,8 @@ idempotency: # 并发等待配置 # ============================================================================= concurrency: - # SSE ping interval during concurrency wait (seconds) - # 并发等待期间的 SSE ping 间隔(秒) + # SSE ping interval during concurrency wait (seconds); 0 disables pings to avoid committing HTTP status early + # 并发等待期间的 SSE ping 间隔(秒);0 禁用 ping,避免提前写入 HTTP 状态码 ping_interval: 10 # ============================================================================= From 4584dcb39228ec606193f63d79b7a465e8751c1e Mon Sep 17 00:00:00 2001 From: r266-tech Date: Wed, 11 Nov 2026 22:49:27 +0800 Subject: [PATCH 13/85] fix(apicompat): retain encrypted function call content --- .../apicompat/responses_to_chatcompletions.go | 3 ++ .../openai_responses_sealed_call_test.go | 49 ++++++++++++++----- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index f33d4792b1..e1a7b88c77 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -503,6 +503,7 @@ type bufferedFuncCall struct { Name string Namespace string EncryptedFunctionArgs json.RawMessage + EncryptedContent string Args strings.Builder } @@ -547,6 +548,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) Name: event.Item.Name, Namespace: event.Item.Namespace, EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs, + EncryptedContent: event.Item.EncryptedContent, }) } case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": @@ -616,6 +618,7 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput { Name: a.funcCalls[i].Name, Namespace: a.funcCalls[i].Namespace, EncryptedFunctionArgs: a.funcCalls[i].EncryptedFunctionArgs, + EncryptedContent: a.funcCalls[i].EncryptedContent, Arguments: a.funcCalls[i].Args.String(), }) } diff --git a/backend/internal/service/openai_responses_sealed_call_test.go b/backend/internal/service/openai_responses_sealed_call_test.go index 31d1406c2d..2235990873 100644 --- a/backend/internal/service/openai_responses_sealed_call_test.go +++ b/backend/internal/service/openai_responses_sealed_call_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" @@ -18,21 +19,26 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { gin.SetMode(gin.TestMode) const arguments = `{"message":"synthetic-sealed-message"}` for _, marker := range []struct { - name string - raw string + name string + raw string + encryptedContent string }{ - {name: "encrypted", raw: `["message"]`}, + {name: "encrypted", raw: `["message"]`, encryptedContent: "synthetic-call-ciphertext"}, {name: "plaintext", raw: `[]`}, {name: "null", raw: `null`}, - {name: "absent"}, + {name: "absent", encryptedContent: "synthetic-call-ciphertext"}, } { for _, shape := range []string{"terminal_output", "item_done", "delta_fallback"} { - for _, passthrough := range []bool{false, true} { - mode := "normal" - if passthrough { - mode = "passthrough" - } - t.Run(marker.name+"/"+shape+"/"+mode, func(t *testing.T) { + for _, mode := range []struct { + name string + passthrough bool + streaming bool + }{ + {name: "normal"}, + {name: "passthrough", passthrough: true}, + {name: "streaming", streaming: true}, + } { + t.Run(marker.name+"/"+shape+"/"+mode.name, func(t *testing.T) { item := map[string]any{ "type": "function_call", "call_id": "call_sealed", "name": "send_message", "namespace": "collaboration", "arguments": arguments, @@ -40,6 +46,9 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { if marker.raw != "" { item["encrypted_function_args"] = json.RawMessage(marker.raw) } + if marker.encryptedContent != "" { + item["encrypted_content"] = marker.encryptedContent + } output := []any{} var frames []string addFrame := func(event map[string]any) { @@ -75,7 +84,11 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { } account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} svc := newCompactBridgeTestService() - if passthrough { + if mode.streaming { + result, err := svc.handleStreamingResponse(context.Background(), resp, c, account, time.Now(), "test-model", "test-model") + require.NoError(t, err) + require.Equal(t, 7, result.usage.InputTokens) + } else if mode.passthrough { result, err := svc.handleNonStreamingResponsePassthrough(context.Background(), resp, c, account, "test-model", "test-model") require.NoError(t, err) require.Equal(t, 7, result.usage.InputTokens) @@ -85,8 +98,15 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { require.Equal(t, 7, result.usage.InputTokens) } require.Equal(t, http.StatusOK, rec.Code) - require.Contains(t, rec.Header().Get("Content-Type"), "application/json") body := rec.Body.Bytes() + if mode.streaming { + require.Contains(t, rec.Header().Get("Content-Type"), "text/event-stream") + _, terminal, ok := extractOpenAISSETerminalEvent(string(body)) + require.True(t, ok) + body = []byte(gjson.GetBytes(terminal, "response").Raw) + } else { + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + } require.Len(t, gjson.GetBytes(body, "output").Array(), 1) call := gjson.GetBytes(body, "output.0") require.Equal(t, "function_call", call.Get("type").String()) @@ -98,6 +118,11 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { } else { require.Equal(t, marker.raw, call.Get("encrypted_function_args").Raw) } + if marker.encryptedContent == "" { + require.False(t, call.Get("encrypted_content").Exists()) + } else { + require.Equal(t, marker.encryptedContent, call.Get("encrypted_content").String()) + } require.Equal(t, "collaboration", call.Get("namespace").String()) }) } From 197109ebce6ab4700052aad261b7200574b8932e Mon Sep 17 00:00:00 2001 From: feeeei Date: Wed, 11 Nov 2026 23:38:12 +0800 Subject: [PATCH 14/85] =?UTF-8?q?fix(auth):=20=E7=99=BB=E5=BD=95=E5=9B=9E?= =?UTF-8?q?=E5=A1=AB=20email=20=E8=BA=AB=E4=BB=BD=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E6=97=B6=E4=B8=8D=E5=86=8D=20panic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ensureEmailAuthIdentity 在 email 身份属于其他账号、并发插入落败或查询出错时 返回 nil,shouldApplyEmailFirstBindDefaults 在判空前读取 identity.Metadata, 导致 RecordSuccessfulLogin 所在的登录请求 panic 并返回 500。判空提到函数开头。 --- backend/internal/service/auth_service.go | 5 +- .../auth_service_identity_sync_test.go | 47 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index 5dbe3bca29..90ba5b3455 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1057,6 +1057,9 @@ func (s *AuthService) shouldApplyEmailFirstBindDefaults( identity *dbent.AuthIdentity, created bool, ) bool { + if identity == nil { + return false + } source := emailAuthIdentitySource(identity.Metadata) if source == "auth_service_login_backfill" { return false @@ -1064,7 +1067,7 @@ func (s *AuthService) shouldApplyEmailFirstBindDefaults( if created { return true } - if s == nil || s.entClient == nil || userID <= 0 || identity == nil || identity.UserID != userID { + if s == nil || s.entClient == nil || userID <= 0 || identity.UserID != userID { return false } if source != "auth_service_dual_write" { diff --git a/backend/internal/service/auth_service_identity_sync_test.go b/backend/internal/service/auth_service_identity_sync_test.go index 59ed8e52b8..ba596718b9 100644 --- a/backend/internal/service/auth_service_identity_sync_test.go +++ b/backend/internal/service/auth_service_identity_sync_test.go @@ -259,6 +259,53 @@ func TestAuthServiceRecordSuccessfulLoginBackfillsEmailIdentity(t *testing.T) { require.Equal(t, user.ID, identity.UserID) } +func TestAuthServiceRecordSuccessfulLogin_EmailIdentityOwnedByAnotherUser(t *testing.T) { + assigner := &authIdentityDefaultSubAssignerStub{} + svc, _, client := newAuthServiceWithEnt(t, map[string]string{ + service.SettingKeyRegistrationEnabled: "true", + service.SettingKeyAuthSourceDefaultEmailBalance: "8.5", + service.SettingKeyAuthSourceDefaultEmailGrantOnFirstBind: "true", + }, assigner) + ctx := context.Background() + + // users.email 唯一索引区分大小写,email 身份按小写邮箱唯一:只差大小写的两个账号共用一条身份。 + owner, err := client.User.Create(). + SetEmail("Shared@Example.com"). + SetPasswordHash("hash"). + SetBalance(1). + SetConcurrency(1). + SetRole(service.RoleUser). + SetStatus(service.StatusActive). + Save(ctx) + require.NoError(t, err) + user, err := client.User.Create(). + SetEmail("shared@example.com"). + SetPasswordHash("hash"). + SetBalance(1). + SetConcurrency(1). + SetRole(service.RoleUser). + SetStatus(service.StatusActive). + Save(ctx) + require.NoError(t, err) + require.NoError(t, client.AuthIdentity.Create(). + SetUserID(owner.ID). + SetProviderType("email"). + SetProviderKey("email"). + SetProviderSubject("shared@example.com"). + SetVerifiedAt(time.Now().UTC()). + SetMetadata(map[string]any{"source": "auth_service_dual_write"}). + Exec(ctx)) + + require.NotPanics(t, func() { svc.RecordSuccessfulLogin(ctx, user.ID) }) + + storedUser, err := client.User.Get(ctx, user.ID) + require.NoError(t, err) + require.NotNil(t, storedUser.LastLoginAt) + require.Equal(t, 1.0, storedUser.Balance) + require.Empty(t, assigner.calls) + require.Equal(t, 0, countProviderGrantRecords(t, client, user.ID, "email", "first_bind")) +} + func TestAuthServiceLogin_DoesNotApplyEmailFirstBindDefaultsWhenBackfillingLegacyEmailIdentity(t *testing.T) { assigner := &authIdentityDefaultSubAssignerStub{} svc, _, client := newAuthServiceWithEnt(t, map[string]string{ From 829bf2cdb9a6a235a5d447ccd92405dbbc123577 Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 12 Nov 2026 04:34:38 +0800 Subject: [PATCH 15/85] =?UTF-8?q?fix(usage):=20=E5=88=86=E7=BB=84=E6=97=A5?= =?UTF-8?q?=E6=B1=87=E6=80=BB=E9=87=8D=E5=BB=BA=E4=B8=8E=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E6=9C=9F=E6=B8=85=E7=90=86=E4=B8=8D=E9=98=BB=E5=A1=9E=20usage?= =?UTF-8?q?=5Flogs=20=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 保留期清理删除过期 usage_logs 时,DELETE 触发器与清理代码把分组日汇总水位拉回到被删记录的日期, 下一次同步随即在持有 usage_group_rollup_state FOR UPDATE 的事务里重算整个保留窗口(生产环境每次约 28 秒,每 6 小时与每次重启各一次)。usage_logs 的插入触发器需要同一行的 FOR KEY SHARE,期间写入全部 排队,超过写入超时后已扣费请求的 usage_log 丢失。后台用量清理、RecomputeRange、分区删除与 DELETE/UPDATE 触发器同样对该行持 FOR UPDATE。 - 保留下界 expired_before:清理把截止点对齐到配置时区的自然日零点,先推进下界再删除;早于下界的记录 变更不触发失效,读路径的历史日桶与尾段都不早于下界。 - 重建拆为登记、计算、发布三个事务:计算阶段只持 FOR KEY SHARE,与写入兼容;登记之后落在重建区间内的 源记录变更记入 build_dirty_from,发布不越过脏日期并续建脏区间。整个重建持会话级 advisory lock。 - DELETE/UPDATE 触发器、后台用量清理、RecomputeRange 与分区删除对状态行只持 FOR KEY SHARE;脏日期已覆盖 的变更不写状态行。 - 分区删除限定父表锁等待 3 秒,超时跳过该分区,过期记录由按行删除清理。 - 分组日界取本地日期实际开始的时刻,覆盖夏令时在零点跳变或回拨的日期;重算只写入不早于起始日的日桶。 --- .../custom_group_usage_rollup_repo.go | 407 ++++++++--- .../dashboard_aggregation_group_usage_test.go | 637 ++++++++++++----- .../repository/dashboard_aggregation_repo.go | 168 ++--- ...age_rollup_nonblocking_integration_test.go | 652 ++++++++++++++++++ ...p_usage_rollup_trigger_integration_test.go | 1 + .../repository/integration_harness_test.go | 2 + .../internal/repository/usage_cleanup_repo.go | 66 +- .../repository/usage_cleanup_repo_test.go | 56 +- .../usage_log_repo_group_summary_test.go | 79 ++- .../service/custom_group_usage_rollup.go | 47 +- .../service/dashboard_aggregation_service.go | 7 +- .../service/request_log_retention_test.go | 79 ++- ...1_group_usage_rollup_nonblocking_build.sql | 159 +++++ .../group_usage_rollup_migration_test.go | 19 + 14 files changed, 1906 insertions(+), 473 deletions(-) create mode 100644 backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go create mode 100644 backend/migrations/251_group_usage_rollup_nonblocking_build.sql diff --git a/backend/internal/repository/custom_group_usage_rollup_repo.go b/backend/internal/repository/custom_group_usage_rollup_repo.go index 1b0e1b2920..f6f61f783b 100644 --- a/backend/internal/repository/custom_group_usage_rollup_repo.go +++ b/backend/internal/repository/custom_group_usage_rollup_repo.go @@ -3,6 +3,8 @@ package repository import ( "context" "database/sql" + "database/sql/driver" + "errors" "fmt" "time" @@ -17,36 +19,43 @@ type groupUsageRollupSnapshot struct { valid bool closedBefore string // date,历史日桶的右开边界 retainedDate string // retained_from 在服务端时区内的日期,历史日桶的左闭边界 - tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点 + tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点,不早于 expired_before } // readGroupUsageRollupSnapshot 读一次汇总水位并在 Go 侧判定有效性。 // // 判定条件与原先 SQL 里的 state_values CTE 完全一致: // 恰好一行、时区名与当前服务端配置相同、且水位不在未来。 +// expired_before 之前的 usage_logs 已超出保留期:无论水位是否有效都不进入尾段, +// 其所在日之前的日桶也不读取。 func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, timezoneName, todayDate string) (groupUsageRollupSnapshot, error) { - epoch := time.Unix(0, 0).UTC() - invalid := groupUsageRollupSnapshot{ - closedBefore: "1970-01-01", - retainedDate: "1970-01-01", - tailStart: epoch, - } - var rowCount int var closedBefore sql.NullString var retainedFrom sql.NullTime var stateTimezone sql.NullString + var expiredBefore sql.NullTime if err := scanSingleRow(ctx, r.sql, ` SELECT COUNT(*), MAX(closed_before)::text, MAX(retained_from), - MAX(timezone_name) + MAX(timezone_name), + MAX(expired_before) FROM usage_group_rollup_state WHERE id = 1 - `, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone); err != nil { + `, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone, &expiredBefore); err != nil { return groupUsageRollupSnapshot{}, fmt.Errorf("读取分组用量汇总水位: %w", err) } + + tailFloor := time.Unix(0, 0).UTC() + if rowCount == 1 && expiredBefore.Valid && expiredBefore.Time.After(tailFloor) { + tailFloor = expiredBefore.Time.UTC() + } + invalid := groupUsageRollupSnapshot{ + closedBefore: "1970-01-01", + retainedDate: "1970-01-01", + tailStart: tailFloor, + } if rowCount != 1 || !closedBefore.Valid || !retainedFrom.Valid || !stateTimezone.Valid || stateTimezone.String != timezoneName || closedBefore.String > todayDate { @@ -58,11 +67,19 @@ func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, t // 水位值解析不出来,按无效处理:宁可多扫一次,也不要算错钱。 return invalid, nil //nolint:nilerr // 与上面的 valid 判定同语义,均降级为全量重算 } + tailStart = tailStart.UTC() + if tailFloor.After(tailStart) { + tailStart = tailFloor + } + retainedDate := service.GroupUsageDate(retainedFrom.Time) + if expiredDate := service.GroupUsageDate(tailFloor); expiredDate > retainedDate { + retainedDate = expiredDate + } return groupUsageRollupSnapshot{ valid: true, closedBefore: closedBefore.String, - retainedDate: service.GroupUsageDate(retainedFrom.Time), - tailStart: tailStart.UTC(), + retainedDate: retainedDate, + tailStart: tailStart, }, nil } @@ -162,94 +179,287 @@ func (r *usageLogRepository) getAllGroupUsageSummaryFromRollups(ctx context.Cont return results, nil } +const ( + groupUsageRollupBuildLockSQL = "SELECT pg_try_advisory_lock(hashtext('usage_group_daily_rollups:build'))" + groupUsageRollupBuildUnlockSQL = "SELECT pg_advisory_unlock(hashtext('usage_group_daily_rollups:build'))" + // groupUsageRollupBuildMaxRounds 限定一次同步内因并发变更重算脏区间的轮数; + // 未收敛的部分保持未发布,由下一次同步继续。 + groupUsageRollupBuildMaxRounds = 3 +) + +var errGroupUsageRollupBuildPreempted = errors.New("分组用量汇总重建登记已被替换") + +// groupUsageRollupBuildPlan 是一轮日桶重建:用 [rowsFrom, rowsBefore) 的 usage_logs +// 重算 [startDate, targetDate) 的日桶,并清理 retainedDate 之前的日桶。 +type groupUsageRollupBuildPlan struct { + startDate string + targetDate string + retainedDate string + rowsFrom time.Time + rowsBefore time.Time + timezoneName string +} + +// groupUsageRollupTxRunner 在一个事务里执行 fn。 +type groupUsageRollupTxRunner func(ctx context.Context, fn func(q sqlExecutor) error) error + // SyncGroupUsageRollups 将服务端配置时区今日以前的用量发布为分组日桶。 +// +// 每轮分三个事务:登记(FOR UPDATE,写入 building_until)、计算(FOR KEY SHARE,重算日桶)、 +// 发布(FOR UPDATE,水位推进到 build_dirty_from 或目标日期)。usage_logs 写入与失效触发器只持 +// FOR KEY SHARE,因此只与登记、发布这两个短事务串行,计算阶段不阻塞写入。 +// 以 *sql.DB 构造时,整个过程持有会话级 advisory lock,同一时刻只有一个重建; +// 以事务构造时,三个阶段在调用方事务内顺序执行。 func (r *dashboardAggregationRepository) SyncGroupUsageRollups(ctx context.Context, todayStart time.Time) error { if r == nil || r.sql == nil { return nil } todayStart = service.GroupUsageTodayStart(todayStart) - if db, ok := r.sql.(*sql.DB); ok { - tx, err := db.BeginTx(ctx, nil) + db, ok := r.sql.(*sql.DB) + if !ok { + return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error { + return fn(r.sql) + }, todayStart) + } + + upToDate, err := groupUsageRollupsUpToDate(ctx, db, todayStart) + if err != nil { + return err + } + if upToDate { + return nil + } + + conn, err := db.Conn(ctx) + if err != nil { + return err + } + var locked bool + if err := scanSingleRow(ctx, conn, groupUsageRollupBuildLockSQL, nil, &locked); err != nil { + // 查询出错时服务端可能已授予锁,丢弃该物理连接以免锁随连接回到连接池。 + discardGroupUsageRollupBuildConn(conn) + return fmt.Errorf("获取分组用量汇总重建锁: %w", err) + } + if !locked { + return conn.Close() + } + defer releaseGroupUsageRollupBuildLock(conn) + + return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error { + tx, err := conn.BeginTx(ctx, nil) if err != nil { return err } - txRepo := newDashboardAggregationRepositoryWithSQL(tx) - if err := txRepo.syncGroupUsageRollupsInTx(ctx, todayStart); err != nil { + if err := fn(tx); err != nil { _ = tx.Rollback() return err } return tx.Commit() - } - return r.syncGroupUsageRollupsInTx(ctx, todayStart) + }, todayStart) } -func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.Context, todayStart time.Time) error { +// releaseGroupUsageRollupBuildLock 释放重建锁;释放失败时丢弃该物理连接,由服务端随会话结束释放锁, +// 避免锁随连接回到连接池。 +func releaseGroupUsageRollupBuildLock(conn *sql.Conn) { + unlockCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + var unlocked bool + if err := scanSingleRow(unlockCtx, conn, groupUsageRollupBuildUnlockSQL, nil, &unlocked); err != nil || !unlocked { + discardGroupUsageRollupBuildConn(conn) + return + } + _ = conn.Close() +} + +// discardGroupUsageRollupBuildConn 关闭底层物理连接而不是归还连接池,会话级锁随会话结束释放。 +func discardGroupUsageRollupBuildConn(conn *sql.Conn) { + _ = conn.Raw(func(any) error { return driver.ErrBadConn }) + _ = conn.Close() +} + +// groupUsageRollupsUpToDate 不加锁地判断今日以前的日桶是否已全部发布。 +func groupUsageRollupsUpToDate(ctx context.Context, q sqlQueryer, todayStart time.Time) (bool, error) { var closedBefore string - var previousRetainedFrom time.Time var stateTimezoneName string - if err := scanSingleRow(ctx, r.sql, ` - SELECT closed_before::text, retained_from, timezone_name + var idle bool + err := scanSingleRow(ctx, q, ` + SELECT closed_before::text, timezone_name, building_until IS NULL + FROM usage_group_rollup_state + WHERE id = 1 + `, nil, &closedBefore, &stateTimezoneName, &idle) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("读取分组用量汇总水位: %w", err) + } + return idle && + closedBefore == service.GroupUsageDate(todayStart) && + stateTimezoneName == service.GroupUsageTimezoneName(), nil +} + +func syncGroupUsageRollupRounds(ctx context.Context, run groupUsageRollupTxRunner, todayStart time.Time) error { + for range groupUsageRollupBuildMaxRounds { + var plan *groupUsageRollupBuildPlan + if err := run(ctx, func(q sqlExecutor) error { + var err error + plan, err = beginGroupUsageRollupBuild(ctx, q, todayStart) + return err + }); err != nil { + return err + } + if plan == nil { + return nil + } + if err := run(ctx, func(q sqlExecutor) error { + return buildGroupUsageRollups(ctx, q, plan) + }); err != nil { + return err + } + var dirty bool + if err := run(ctx, func(q sqlExecutor) error { + var err error + dirty, err = publishGroupUsageRollups(ctx, q, plan) + return err + }); err != nil { + return err + } + if !dirty { + return nil + } + } + return nil +} + +// beginGroupUsageRollupBuild 在 FOR UPDATE 下确定重建区间并登记 building_until。 +// 日桶已发布到今日时返回 nil。 +func beginGroupUsageRollupBuild(ctx context.Context, q sqlExecutor, todayStart time.Time) (*groupUsageRollupBuildPlan, error) { + var closedBefore string + var retainedFrom time.Time + var stateTimezoneName string + var expiredBefore time.Time + var buildingUntil sql.NullString + if err := scanSingleRow(ctx, q, ` + SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text FROM usage_group_rollup_state WHERE id = 1 FOR UPDATE - `, nil, &closedBefore, &previousRetainedFrom, &stateTimezoneName); err != nil { - return fmt.Errorf("读取分组用量汇总水位: %w", err) + `, nil, &closedBefore, &retainedFrom, &stateTimezoneName, &expiredBefore, &buildingUntil); err != nil { + return nil, fmt.Errorf("读取分组用量汇总水位: %w", err) } todayDate := service.GroupUsageDate(todayStart) timezoneName := service.GroupUsageTimezoneName() timezoneChanged := stateTimezoneName != timezoneName - var closedTime time.Time if !timezoneChanged { - var err error - closedTime, err = service.ParseGroupUsageDate(closedBefore) + closedTime, err := service.ParseGroupUsageDate(closedBefore) if err != nil { - return fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err) + return nil, fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err) } todayDateTime, err := service.ParseGroupUsageDate(todayDate) if err != nil { - return err + return nil, err } if closedTime.After(todayDateTime) { - return fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore) + return nil, fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore) } if closedBefore == todayDate { - return nil + if buildingUntil.Valid { + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET building_until = NULL, + build_dirty_from = NULL, + updated_at = NOW() + WHERE id = 1 + `); err != nil { + return nil, fmt.Errorf("清除分组用量汇总重建登记: %w", err) + } + } + return nil, nil } } - var earliest sql.NullTime - if err := scanSingleRow(ctx, r.sql, "SELECT MIN(created_at) FROM usage_logs", nil, &earliest); err != nil { - return fmt.Errorf("读取最早用量记录: %w", err) - } - retainedFrom := todayStart - if earliest.Valid { - retainedFrom = earliest.Time.UTC() + // 可读日桶从 retained_from 所在日开始,且不早于保留下界。 + if retainedFrom.Before(expiredBefore) { + retainedFrom = expiredBefore } + // closed_before 不晚于保留起点时,可读日桶为空,按保留起点全量重建;否则从水位续建。 retainedDate := service.GroupUsageDate(retainedFrom) - retainedDateTime, err := service.ParseGroupUsageDate(retainedDate) - if err != nil { - return err - } - rebuildStartDate := retainedDate - if !timezoneChanged && closedTime.After(retainedDateTime) { - rebuildStartDate = closedBefore - } - rebuildStart, err := service.ParseGroupUsageDate(rebuildStartDate) - if err != nil { - return err + startDate := closedBefore + if timezoneChanged || closedBefore <= retainedDate { + var earliest sql.NullTime + if err := scanSingleRow(ctx, q, ` + SELECT MIN(created_at) + FROM usage_logs + WHERE created_at >= $1 + `, []any{expiredBefore.UTC()}, &earliest); err != nil { + return nil, fmt.Errorf("读取最早用量记录: %w", err) + } + retainedFrom = todayStart + if earliest.Valid { + retainedFrom = earliest.Time.UTC() + } + retainedDate = service.GroupUsageDate(retainedFrom) + startDate = retainedDate } - if _, err := r.sql.ExecContext(ctx, ` + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET closed_before = $1::date, + retained_from = $2, + timezone_name = $3, + building_until = $4::date, + build_dirty_from = NULL, + updated_at = NOW() + WHERE id = 1 + `, startDate, retainedFrom.UTC(), timezoneName, todayDate); err != nil { + return nil, fmt.Errorf("登记分组用量汇总重建: %w", err) + } + + startTime, err := service.ParseGroupUsageDate(startDate) + if err != nil { + return nil, err + } + rowsFrom := startTime.UTC() + if expiredBefore.After(rowsFrom) { + rowsFrom = expiredBefore.UTC() + } + return &groupUsageRollupBuildPlan{ + startDate: startDate, + targetDate: todayDate, + retainedDate: retainedDate, + rowsFrom: rowsFrom, + rowsBefore: todayStart.UTC(), + timezoneName: timezoneName, + }, nil +} + +// buildGroupUsageRollups 重算 [startDate, targetDate) 的日桶,只写入本地日期不早于 startDate 的桶。 +// 状态行只持 FOR KEY SHARE,与 usage_logs 写入和失效触发器兼容;登记与发布的 FOR UPDATE 须等待本事务结束。 +func buildGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) error { + var buildingUntil sql.NullString + var stateTimezoneName string + if err := scanSingleRow(ctx, q, ` + SELECT building_until::text, timezone_name + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE + `, nil, &buildingUntil, &stateTimezoneName); err != nil { + return fmt.Errorf("读取分组用量汇总重建登记: %w", err) + } + if !buildingUntil.Valid || buildingUntil.String != plan.targetDate || stateTimezoneName != plan.timezoneName { + return errGroupUsageRollupBuildPreempted + } + + if _, err := q.ExecContext(ctx, ` DELETE FROM usage_group_daily_rollups WHERE bucket_date < $1::date - OR (bucket_date >= $2::date AND bucket_date < $3::date) - OR bucket_date >= $3::date - `, retainedDate, rebuildStartDate, todayDate); err != nil { + OR bucket_date >= $2::date + `, plan.retainedDate, plan.startDate); err != nil { return fmt.Errorf("清理分组用量日桶: %w", err) } - if _, err := r.sql.ExecContext(ctx, ` + if _, err := q.ExecContext(ctx, ` INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost, computed_at) SELECT (created_at AT TIME ZONE $3::text)::date AS bucket_date, @@ -260,51 +470,82 @@ func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.C WHERE group_id IS NOT NULL AND created_at >= $1 AND created_at < $2 + AND (created_at AT TIME ZONE $3::text)::date >= $4::date GROUP BY 1, 2 ON CONFLICT (bucket_date, group_id) DO UPDATE SET actual_cost = EXCLUDED.actual_cost, computed_at = EXCLUDED.computed_at - `, rebuildStart.UTC(), todayStart.UTC(), timezoneName); err != nil { + `, plan.rowsFrom, plan.rowsBefore, plan.timezoneName, plan.startDate); err != nil { return fmt.Errorf("重建分组用量日桶: %w", err) } - - if _, err := r.sql.ExecContext(ctx, ` - UPDATE usage_group_rollup_state - SET closed_before = $1::date, - retained_from = $2, - timezone_name = $3, - updated_at = NOW() - WHERE id = 1 - `, todayDate, retainedFrom, timezoneName); err != nil { - return fmt.Errorf("更新分组用量汇总水位: %w", err) - } return nil } -func lockGroupUsageRollupState(ctx context.Context, tx *sql.Tx) error { - var id int16 - if err := tx.QueryRowContext(ctx, ` - SELECT id +// publishGroupUsageRollups 在 FOR UPDATE 下发布本轮结果并清除登记,返回是否存在需要重算的脏区间。 +// +// 登记之后 [startDate, targetDate) 内的源记录变更都记入了 build_dirty_from,[startDate, build_dirty_from) +// 的日桶与计算快照一致;水位低于 startDate 说明有未记脏的失效,此时发布不越过当前水位。 +func publishGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) (bool, error) { + var closedBefore string + var buildingUntil sql.NullString + var dirtyFrom sql.NullString + if err := scanSingleRow(ctx, q, ` + SELECT closed_before::text, building_until::text, build_dirty_from::text FROM usage_group_rollup_state WHERE id = 1 FOR UPDATE - `).Scan(&id); err != nil { - return fmt.Errorf("锁定分组用量汇总水位: %w", err) + `, nil, &closedBefore, &buildingUntil, &dirtyFrom); err != nil { + return false, fmt.Errorf("读取分组用量汇总重建登记: %w", err) + } + if !buildingUntil.Valid || buildingUntil.String != plan.targetDate { + return false, errGroupUsageRollupBuildPreempted + } + + publishBefore := plan.targetDate + dirty := false + if dirtyFrom.Valid && dirtyFrom.String < publishBefore { + publishBefore = dirtyFrom.String + dirty = true + } + if closedBefore < plan.startDate && closedBefore < publishBefore { + publishBefore = closedBefore + dirty = true + } + + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET closed_before = $1::date, + building_until = NULL, + build_dirty_from = NULL, + updated_at = NOW() + WHERE id = 1 + `, publishBefore); err != nil { + return false, fmt.Errorf("发布分组用量汇总水位: %w", err) + } + return dirty, nil +} + +// expireGroupUsageRollupsBefore 把保留下界推进到 cutoff:早于 cutoff 的 usage_logs 不属于任何可读日桶, +// 删除它们不触发失效。cutoff 须为服务端配置时区的自然日零点,使边界日桶不包含被删除的记录。 +func expireGroupUsageRollupsBefore(ctx context.Context, q sqlExecutor, cutoff time.Time) error { + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET expired_before = GREATEST(expired_before, $1), + retained_from = GREATEST(retained_from, $1), + updated_at = NOW() + WHERE id = 1 + `, cutoff.UTC()); err != nil { + return fmt.Errorf("推进分组用量汇总保留下界: %w", err) } return nil } -func invalidateGroupUsageRollupsAt(ctx context.Context, tx *sql.Tx, affectedAt time.Time) error { - timezoneName := service.GroupUsageTimezoneName() - _, err := tx.ExecContext(ctx, ` - UPDATE usage_group_rollup_state - SET closed_before = LEAST( - closed_before, - ($1::timestamptz AT TIME ZONE $2::text)::date - ), - updated_at = NOW() - WHERE id = 1 - `, affectedAt.UTC(), timezoneName) +// invalidateGroupUsageRollupsAt 使 affectedAt 所在自然日及之后的日桶失效;早于保留下界的时刻不生效。 +func invalidateGroupUsageRollupsAt(ctx context.Context, q sqlExecutor, affectedAt time.Time) error { + _, err := q.ExecContext(ctx, + "SELECT invalidate_group_usage_rollups_at($1, $2)", + affectedAt.UTC(), service.GroupUsageTimezoneName(), + ) return err } diff --git a/backend/internal/repository/dashboard_aggregation_group_usage_test.go b/backend/internal/repository/dashboard_aggregation_group_usage_test.go index 40bca32bc4..31365c156b 100644 --- a/backend/internal/repository/dashboard_aggregation_group_usage_test.go +++ b/backend/internal/repository/dashboard_aggregation_group_usage_test.go @@ -5,61 +5,146 @@ package repository import ( "context" "database/sql" + "database/sql/driver" "errors" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/lib/pq" "github.com/stretchr/testify/require" ) -func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsAtCurrentDate(t *testing.T) { +const ( + groupRollupPrecheckQuery = `SELECT closed_before::text, timezone_name, building_until IS NULL` + groupRollupLockQuery = `SELECT pg_try_advisory_lock\(hashtext\('usage_group_daily_rollups:build'\)\)` + groupRollupUnlockQuery = `SELECT pg_advisory_unlock\(hashtext\('usage_group_daily_rollups:build'\)\)` + groupRollupBeginQuery = `(?s)SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text.*FOR UPDATE` + groupRollupBuildQuery = `(?s)SELECT building_until::text, timezone_name.*FOR KEY SHARE` + groupRollupPublishQuery = `(?s)SELECT closed_before::text, building_until::text, build_dirty_from::text.*FOR UPDATE` + groupRollupRegisterExec = `(?s)UPDATE usage_group_rollup_state.*building_until = \$4::date` + groupRollupPublishExec = `(?s)UPDATE usage_group_rollup_state.*SET closed_before = \$1::date,\s+building_until = NULL` + groupRollupExpireExec = `(?s)UPDATE usage_group_rollup_state.*expired_before = GREATEST\(expired_before, \$1\)` + groupRollupInvalidateSQL = `SELECT invalidate_group_usage_rollups_at\(\$1, \$2\)` +) + +var groupRollupEpoch = time.Unix(0, 0).UTC() + +func expectGroupRollupPrecheck(mock sqlmock.Sqlmock, closedBefore, timezoneName string, idle bool) { + mock.ExpectQuery(groupRollupPrecheckQuery). + WillReturnRows(sqlmock.NewRows([]string{"closed_before", "timezone_name", "idle"}). + AddRow(closedBefore, timezoneName, idle)) +} + +func expectGroupRollupLock(mock sqlmock.Sqlmock, locked bool) { + mock.ExpectQuery(groupRollupLockQuery). + WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(locked)) +} + +func expectGroupRollupUnlock(mock sqlmock.Sqlmock) { + mock.ExpectQuery(groupRollupUnlockQuery). + WillReturnRows(sqlmock.NewRows([]string{"unlocked"}).AddRow(true)) +} + +func groupRollupBeginRows(closedBefore string, retainedFrom time.Time, timezoneName string, expiredBefore time.Time, buildingUntil any) *sqlmock.Rows { + return sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name", "expired_before", "building_until"}). + AddRow(closedBefore, retainedFrom, timezoneName, expiredBefore, buildingUntil) +} + +// expectGroupRollupRound 期望一轮完整的登记、计算、发布。 +func expectGroupRollupRound( + mock sqlmock.Sqlmock, + begin *sqlmock.Rows, + minCreatedAt *sqlmock.Rows, + minCreatedAfter time.Time, + register []any, + deleteArgs []any, + insertArgs []any, + publishRows *sqlmock.Rows, + publishBefore string, +) { + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBeginQuery).WillReturnRows(begin) + if minCreatedAt != nil { + mock.ExpectQuery(`(?s)SELECT MIN\(created_at\)\s+FROM usage_logs\s+WHERE created_at >= \$1`). + WithArgs(minCreatedAfter). + WillReturnRows(minCreatedAt) + } + mock.ExpectExec(groupRollupRegisterExec). + WithArgs(toDriverValues(register)...). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBuildQuery). + WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(register[3], register[2])) + mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). + WithArgs(toDriverValues(deleteArgs)...). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). + WithArgs(toDriverValues(append(append([]any{}, insertArgs...), register[0]))...). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + mock.ExpectBegin() + mock.ExpectQuery(groupRollupPublishQuery).WillReturnRows(publishRows) + mock.ExpectExec(groupRollupPublishExec). + WithArgs(publishBefore). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() +} + +func toDriverValues(values []any) []driver.Value { + args := make([]driver.Value, 0, len(values)) + for _, value := range values { + args = append(args, sqlmockValue{value: value}) + } + return args +} + +// sqlmockValue 按时刻比较 time.Time(忽略 Location),其余值按相等比较。 +type sqlmockValue struct{ value any } + +func (v sqlmockValue) Match(actual driver.Value) bool { + if expectedTime, ok := v.value.(time.Time); ok { + actualTime, ok := actual.(time.Time) + return ok && actualTime.Equal(expectedTime) + } + return actual == v.value +} + +func publishRows(closedBefore, buildingUntil string, dirtyFrom any) *sqlmock.Rows { + return sqlmock.NewRows([]string{"closed_before", "building_until", "build_dirty_from"}). + AddRow(closedBefore, buildingUntil, dirtyFrom) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsWithoutLockingAtCurrentDate(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-08-14", time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectCommit() + expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", true) require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) { - useGroupUsageRepositoryTestTimezone(t, "America/New_York") - +func TestDashboardAggregationRepositorySyncGroupUsageRollupsSkipsWhenAnotherBuildHoldsLock(t *testing.T) { + setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) - retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-03-09", time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`). - WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom)) - mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). - WithArgs("2026-03-01", "2026-03-01", "2026-03-09"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). - WithArgs(retainedFrom, todayStart, "America/New_York"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs("2026-03-09", retainedFrom, "America/New_York"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, false) require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLast(t *testing.T) { +func TestDashboardAggregationRepositorySyncGroupUsageRollupsBuildsAndPublishesInSeparateTransactions(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) @@ -67,22 +152,209 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLa retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) rebuildStart := time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC) + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-13"}, + []any{rebuildStart, todayStart, "Asia/Shanghai"}, + publishRows("2026-08-13", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsDirtyRangeBeforeFullPublish(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-11", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + // 第一轮计算期间有 08-12 的迟到写入:只发布到 08-12。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-11", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-11", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-11"}, + []any{time.Date(2026, 8, 10, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-11", "2026-08-14", "2026-08-12"), + "2026-08-12", + ) + // 第二轮只重算脏日期之后的区间。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-12"}, + []any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-12", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsStopsAfterMaxRoundsWithoutOverPublishing(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-12", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + for range groupUsageRollupBuildMaxRounds { + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-12"}, + []any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-12", "2026-08-14", "2026-08-12"), + "2026-08-12", + ) + } + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishKeepsUnmarkedInvalidation(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + // 计算期间水位被后退到 08-10 而没有记脏:发布不越过 08-10。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-13"}, + []any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-10", "2026-08-14", nil), + "2026-08-10", + ) + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-10", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-10", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-10"}, + []any{time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-10", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) { + useGroupUsageRepositoryTestTimezone(t, "America/New_York") + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-03-09", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-03-09", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil), + sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom), groupRollupEpoch, + []any{"2026-03-01", retainedFrom, "America/New_York", "2026-03-09"}, + []any{"2026-03-01", "2026-03-01"}, + []any{retainedFrom, todayStart, "America/New_York"}, + publishRows("2026-03-01", "2026-03-09", nil), + "2026-03-09", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsFullRebuildExcludesExpiredRows(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + // 保留下界不在 Asia/Shanghai 的日界上(例如在其他时区下推进):重建只计入下界之后的记录。 + expiredBefore := time.Date(2026, 5, 1, 18, 0, 0, 0, time.UTC) + earliestRetained := time.Date(2026, 5, 1, 19, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "1970-01-01", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + expectGroupRollupRound(mock, + groupRollupBeginRows("1970-01-01", groupRollupEpoch, "Asia/Shanghai", expiredBefore, nil), + sqlmock.NewRows([]string{"min"}).AddRow(earliestRetained), expiredBefore, + []any{"2026-05-02", earliestRetained, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-02", "2026-05-02"}, + []any{expiredBefore, todayStart, "Asia/Shanghai"}, + publishRows("2026-05-02", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsKeepsRetainedFromAtExpiredFloor(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + staleRetainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + expiredBefore := time.Date(2026, 5, 14, 16, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + // retained_from 早于保留下界(例如被其他版本的同步改写):登记与清理都以保留下界为起点。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-13", staleRetainedFrom, "Asia/Shanghai", expiredBefore, nil), + nil, time.Time{}, + []any{"2026-08-13", expiredBefore, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-15", "2026-08-13"}, + []any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-13", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsClearsStaleBuildMarkWhenPublished(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", false) + expectGroupRollupLock(mock, true) mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-08-13", time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`). - WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom)) - mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). - WithArgs("2026-05-01", "2026-08-13", "2026-08-14"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). - WithArgs(rebuildStart, todayStart, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 2)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs("2026-08-14", retainedFrom, "Asia/Shanghai"). + mock.ExpectQuery(groupRollupBeginQuery). + WillReturnRows(groupRollupBeginRows("2026-08-14", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, "2026-08-14")) + mock.ExpectExec(`(?s)UPDATE usage_group_rollup_state\s+SET building_until = NULL`). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() + expectGroupRollupUnlock(mock) require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) require.NoError(t, mock.ExpectationsWereMet()) @@ -94,17 +366,44 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsRejectsFutureWaterma repo := newDashboardAggregationRepositoryWithSQL(db) todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + expectGroupRollupPrecheck(mock, "2026-08-15", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-08-15", time.Unix(0, 0).UTC(), "Asia/Shanghai")) + mock.ExpectQuery(groupRollupBeginQuery). + WillReturnRows(groupRollupBeginRows("2026-08-15", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil)) mock.ExpectRollback() + expectGroupRollupUnlock(mock) err := repo.SyncGroupUsageRollups(context.Background(), todayStart) require.ErrorContains(t, err, "未来") require.NoError(t, mock.ExpectationsWereMet()) } +func TestDashboardAggregationRepositorySyncGroupUsageRollupsAbortsWhenBuildMarkReplaced(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBeginQuery). + WillReturnRows(groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil)) + mock.ExpectExec(groupRollupRegisterExec).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBuildQuery). + WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(nil, "Asia/Shanghai")) + mock.ExpectRollback() + expectGroupRollupUnlock(mock) + + err := repo.SyncGroupUsageRollups(context.Background(), todayStart) + require.ErrorIs(t, err, errGroupUsageRollupBuildPreempted) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBeforeDashboardRebuild(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) @@ -112,12 +411,10 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) end := start.Add(time.Hour) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). + mock.ExpectExec(groupRollupInvalidateSQL). WithArgs(start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectBegin() mock.ExpectExec(`DELETE FROM usage_dashboard_hourly`). WillReturnError(sql.ErrConnDone) mock.ExpectRollback() @@ -127,25 +424,17 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeCommit(t *testing.T) { +func TestDashboardAggregationRepositoryRecomputeRangeLeavesGroupRollupRebuildToSync(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) end := start.Add(time.Hour) - fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) - repo.clock = func() time.Time { return fixedNow } - todayStart := service.GroupUsageTodayStart(fixedNow) - startDate := service.GroupUsageDate(start) - rebuildStart, err := service.ParseGroupUsageDate(startDate) - require.NoError(t, err) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). + mock.ExpectExec(groupRollupInvalidateSQL). WithArgs(start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectBegin() for _, query := range []string{ `DELETE FROM usage_dashboard_hourly WHERE`, `DELETE FROM usage_dashboard_hourly_users WHERE`, @@ -158,71 +447,67 @@ func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeC } { mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 1)) } - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow(startDate, time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`). - WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(start)) - mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). - WithArgs(startDate, startDate, service.GroupUsageDate(todayStart)). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). - WithArgs(rebuildStart.UTC(), todayStart.UTC(), "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(service.GroupUsageDate(todayStart), start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() require.NoError(t, repo.RecomputeRange(context.Background(), start, end)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedInvalidatesEachBatchAndSyncs(t *testing.T) { +func TestDashboardAggregationRepositoryRecomputeRangeStopsWhenInvalidationFails(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) - earliestDeletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC) + start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) + + mock.ExpectExec(groupRollupInvalidateSQL). + WithArgs(start, "Asia/Shanghai"). + WillReturnError(sql.ErrConnDone) + + err := repo.RecomputeRange(context.Background(), start, start.Add(time.Hour)) + require.ErrorIs(t, err, sql.ErrConnDone) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositoryCleanupUsageLogsExpiresWholeDaysBeforeDeleting(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + // 2026-07-01 13:00 +08 对齐到 2026-07-01 00:00 +08。 + cutoff := time.Date(2026, 7, 1, 5, 0, 0, 0, time.UTC) + alignedCutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) repo.clock = func() time.Time { return fixedNow } - todayStart := service.GroupUsageTodayStart(fixedNow) + mock.ExpectExec(groupRollupExpireExec). + WithArgs(alignedCutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`SELECT EXISTS`). WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`). - WithArgs(cutoff, usageLogsCleanupBatchSize). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}). - AddRow(earliestDeletedAt.Add(time.Hour)). - AddRow(earliestDeletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(earliestDeletedAt, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectCommit() + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs`). + WithArgs(alignedCutoff, usageLogsCleanupBatchSize). + WillReturnResult(sqlmock.NewResult(0, usageLogsCleanupBatchSize)) + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`). + WithArgs(alignedCutoff, usageLogsCleanupBatchSize). + WillReturnResult(sqlmock.NewResult(0, 3)) + expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true) require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvalidatesEachDropBeforeSync(t *testing.T) { - setGroupUsageRollupTestTimezone(t) +func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedInvalidatesRetainedRowsAfterDrop(t *testing.T) { + useGroupUsageRepositoryTestTimezone(t, "UTC") db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC) - aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC) - juneStart := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC) - fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) + cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) + fixedNow := time.Date(2026, 9, 29, 8, 0, 0, 0, time.UTC) repo.clock = func() time.Time { return fixedNow } - todayStart := service.GroupUsageTodayStart(fixedNow) + // 6 月分区建于 UTC-5 会话时区,上界是 07-01 05:00 UTC,包含保留下界之后的记录。 + retainedInJunePartition := time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC) + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`SELECT EXISTS`). WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) mock.ExpectQuery(`SELECT c.relname`). @@ -232,78 +517,120 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvali AddRow("usage_logs_202604"). AddRow("usage_logs_202607")) - for _, partition := range []struct { - name string - start time.Time - }{ - {name: "usage_logs_202604", start: aprilStart}, - {name: "usage_logs_202606", start: juneStart}, - } { - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(partition.start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`DROP TABLE IF EXISTS "` + partition.name + `"`). - WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectCommit() - } - // The boundary partition is pruned by exact timestamp. tableoid is required - // because ctid alone can also identify a retained row in another partition. + // 4 月分区全部早于保留下界:直接删除。 mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN.*RETURNING created_at`). + mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604" WHERE created_at >= \$1`). + WithArgs(cutoff). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) + mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectCommit() + // 6 月分区含保留下界之后的记录:删除后按其中最早时刻失效。 + mock.ExpectBegin() + mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202606" WHERE created_at >= \$1`). + WithArgs(cutoff). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedInJunePartition)) + mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202606"`). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(groupRollupInvalidateSQL). + WithArgs(retainedInJunePartition, "UTC"). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectCommit() + // 边界分区按精确时间删除;tableoid 区分不同分区里相同的 ctid。 + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN`). WithArgs(cutoff, usageLogsCleanupBatchSize). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(cutoff.Add(-time.Hour))) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(cutoff.Add(-time.Hour), "Asia/Shanghai"). WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectCommit() + expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "UTC", true) require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedFailureRollsBackWithoutSync(t *testing.T) { +func TestDashboardAggregationRepositoryCleanupUsageLogsStopsWhenExpireFails(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) - deletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC) + cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) - mock.ExpectQuery(`SELECT EXISTS`). - WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs.*RETURNING created_at`). - WithArgs(cutoff, usageLogsCleanupBatchSize). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(deletedAt, "Asia/Shanghai"). + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). WillReturnError(sql.ErrConnDone) - mock.ExpectRollback() err := repo.CleanupUsageLogs(context.Background(), cutoff) require.ErrorIs(t, err, sql.ErrConnDone) require.NoError(t, mock.ExpectationsWereMet()) } +func TestDashboardAggregationRepositoryCleanupUsageLogsBatchFailureStopsWithoutSync(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) + + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`SELECT EXISTS`). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`). + WithArgs(cutoff, usageLogsCleanupBatchSize). + WillReturnError(sql.ErrConnDone) + + err := repo.CleanupUsageLogs(context.Background(), cutoff) + require.ErrorIs(t, err, sql.ErrConnDone) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositoryCleanupUsageLogsSkipsPartitionWhenDropLockTimesOut(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC) + fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) + repo.clock = func() time.Time { return fixedNow } + + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`SELECT EXISTS`). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + mock.ExpectQuery(`SELECT c.relname`). + WillReturnRows(sqlmock.NewRows([]string{"relname"}).AddRow("usage_logs_202604")) + mock.ExpectBegin() + mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) + mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). + WillReturnError(&pq.Error{Code: "55P03", Message: "canceling statement due to lock timeout"}) + mock.ExpectRollback() + // 分区保留,其中的过期记录由按行删除清理。 + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`). + WithArgs(cutoff, usageLogsCleanupBatchSize). + WillReturnResult(sqlmock.NewResult(0, 5)) + expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true) + + require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff)) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBackAndStops(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC) - aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC) + cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC) dropErr := errors.New("drop partition failed") + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`SELECT EXISTS`). WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) mock.ExpectQuery(`SELECT c.relname`). @@ -311,11 +638,11 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBack AddRow("usage_logs_202606"). AddRow("usage_logs_202604")) mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(aprilStart, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). WillReturnError(dropErr) mock.ExpectRollback() diff --git a/backend/internal/repository/dashboard_aggregation_repo.go b/backend/internal/repository/dashboard_aggregation_repo.go index 347600df05..7a0351f7f4 100644 --- a/backend/internal/repository/dashboard_aggregation_repo.go +++ b/backend/internal/repository/dashboard_aggregation_repo.go @@ -3,6 +3,7 @@ package repository import ( "context" "database/sql" + "errors" "fmt" "log" "sort" @@ -20,6 +21,9 @@ type dashboardAggregationRepository struct { } const usageLogsCleanupBatchSize = 10000 + +// usageLogsPartitionDropLockTimeout 限定删除分区时等待父表锁的时长。 +const usageLogsPartitionDropLockTimeout = 3 * time.Second const usageBillingDedupCleanupBatchSize = 10000 // NewDashboardAggregationRepository 创建仪表盘预聚合仓储。 @@ -131,29 +135,22 @@ func (r *dashboardAggregationRepository) RecomputeRange(ctx context.Context, sta dayEnd = dayEnd.Add(24 * time.Hour) } + // 分组日桶从 start 所在自然日起失效,由后台同步重建;失效语句独立提交,不与看板重算共享事务。 + if err := invalidateGroupUsageRollupsAt(ctx, r.sql, start); err != nil { + return err + } + // 尽量使用事务保证范围内的一致性(允许在非 *sql.DB 的情况下退化为非事务执行)。 if db, ok := r.sql.(*sql.DB); ok { tx, err := db.BeginTx(ctx, nil) if err != nil { return err } - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - _ = tx.Rollback() - return err - } - if err := invalidateGroupUsageRollupsAt(ctx, tx, start); err != nil { - _ = tx.Rollback() - return err - } txRepo := newDashboardAggregationRepositoryWithSQL(tx) if err := txRepo.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd); err != nil { _ = tx.Rollback() return err } - if err := txRepo.syncGroupUsageRollupsInTx(ctx, service.GroupUsageTodayStart(r.now())); err != nil { - _ = tx.Rollback() - return err - } return tx.Commit() } return r.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd) @@ -230,7 +227,13 @@ func (r *dashboardAggregationRepository) CleanupAggregates(ctx context.Context, return nil } +// CleanupUsageLogs 删除服务端配置时区内 cutoff 所在自然日零点之前的 usage_logs。 +// 删除前先把分组日汇总的保留下界推进到该零点,被删除的记录不触发日桶失效。 func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, cutoff time.Time) error { + cutoff = service.GroupUsageTodayStart(cutoff) + if err := expireGroupUsageRollupsBefore(ctx, r.sql, cutoff); err != nil { + return err + } isPartitioned, err := r.isUsageLogsPartitioned(ctx) if err != nil { return err @@ -249,19 +252,7 @@ func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, c } func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Context, cutoff time.Time) error { - db, transactional := r.sql.(*sql.DB) for { - if transactional { - affected, err := cleanupUsageLogsBatchWithRollupInvalidation(ctx, db, cutoff) - if err != nil { - return err - } - if affected < usageLogsCleanupBatchSize { - return nil - } - continue - } - res, err := r.sql.ExecContext(ctx, ` WITH victims AS ( SELECT tableoid, ctid @@ -286,66 +277,6 @@ func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Con } } -func cleanupUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, cutoff time.Time) (int64, error) { - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return 0, err - } - rollback := func(err error) (int64, error) { - _ = tx.Rollback() - return 0, err - } - - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - return rollback(err) - } - rows, err := tx.QueryContext(ctx, ` - WITH victims AS ( - SELECT tableoid, ctid - FROM usage_logs - WHERE created_at < $1 - ORDER BY created_at ASC, id ASC - LIMIT $2 - ) - DELETE FROM usage_logs - WHERE (tableoid, ctid) IN (SELECT tableoid, ctid FROM victims) - RETURNING created_at - `, cutoff.UTC(), usageLogsCleanupBatchSize) - if err != nil { - return rollback(err) - } - - var affected int64 - var earliestDeletedAt time.Time - for rows.Next() { - var deletedAt time.Time - if err := rows.Scan(&deletedAt); err != nil { - _ = rows.Close() - return rollback(err) - } - affected++ - if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) { - earliestDeletedAt = deletedAt - } - } - if err := rows.Err(); err != nil { - _ = rows.Close() - return rollback(err) - } - if err := rows.Close(); err != nil { - return rollback(err) - } - if affected > 0 { - if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil { - return rollback(err) - } - } - if err := tx.Commit(); err != nil { - return 0, err - } - return affected, nil -} - func (r *dashboardAggregationRepository) CleanupUsageBillingDedup(ctx context.Context, cutoff time.Time) error { for { res, err := r.sql.ExecContext(ctx, ` @@ -630,40 +561,69 @@ func (r *dashboardAggregationRepository) dropUsageLogsPartitions(ctx context.Con sort.Slice(partitions, func(i, j int) bool { return partitions[i].month.Before(partitions[j].month) }) - if db, ok := r.sql.(*sql.DB); ok { - for _, partition := range partitions { - if err := dropUsageLogsPartitionWithRollupInvalidation(ctx, db, partition.name, partition.month); err != nil { - return err - } - } - return nil - } for _, partition := range partitions { - if _, err := r.sql.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(partition.name))); err != nil { + if err := r.dropUsageLogsPartition(ctx, partition.name); err != nil { + // 父表锁等待超时:保留该分区,其中的过期记录由随后的按行删除清理,空分区在下次清理时删除。 + if isPostgresLockNotAvailable(err) { + log.Printf("[DashboardAggregation] 删除分区 %s 等待锁超时,本次改为按行删除", partition.name) + continue + } return err } } return nil } -func dropUsageLogsPartitionWithRollupInvalidation(ctx context.Context, db *sql.DB, name string, monthStart time.Time) error { +func isPostgresLockNotAvailable(err error) bool { + var pqErr *pq.Error + return errors.As(err, &pqErr) && pqErr.Code == "55P03" +} + +// dropUsageLogsPartition 删除一个 usage_logs 月分区。分区内不早于保留下界的记录参与分组日汇总, +// 删除后按其中最早的时刻使日桶失效;状态行的 FOR KEY SHARE 使失效与重建的登记、发布串行。 +// DROP 需要父表 ACCESS EXCLUSIVE 锁,排队期间会挡住 usage_logs 写入,因此限定锁等待时长。 +func (r *dashboardAggregationRepository) dropUsageLogsPartition(ctx context.Context, name string) error { + drop := func(q sqlExecutor) error { + var expiredBefore time.Time + if err := scanSingleRow(ctx, q, ` + SELECT expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE + `, nil, &expiredBefore); err != nil { + return fmt.Errorf("读取分组用量汇总保留下界: %w", err) + } + var earliestRetained sql.NullTime + if err := scanSingleRow(ctx, q, + fmt.Sprintf("SELECT MIN(created_at) FROM %s WHERE created_at >= $1", pq.QuoteIdentifier(name)), + []any{expiredBefore.UTC()}, &earliestRetained, + ); err != nil { + return err + } + if _, err := q.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil { + return err + } + if earliestRetained.Valid { + return invalidateGroupUsageRollupsAt(ctx, q, earliestRetained.Time) + } + return nil + } + + db, ok := r.sql.(*sql.DB) + if !ok { + return drop(r.sql) + } tx, err := db.BeginTx(ctx, nil) if err != nil { return err } - rollback := func(err error) error { + if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL lock_timeout = '%dms'", usageLogsPartitionDropLockTimeout.Milliseconds())); err != nil { _ = tx.Rollback() return err } - - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - return rollback(err) - } - if err := invalidateGroupUsageRollupsAt(ctx, tx, monthStart); err != nil { - return rollback(err) - } - if _, err := tx.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil { - return rollback(err) + if err := drop(tx); err != nil { + _ = tx.Rollback() + return err } return tx.Commit() } diff --git a/backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go b/backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go new file mode 100644 index 0000000000..1aec81eb0e --- /dev/null +++ b/backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go @@ -0,0 +1,652 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "fmt" + "net/url" + "testing" + "time" + + "github.com/lib/pq" + "github.com/stretchr/testify/require" +) + +// 计算阶段持有状态行 FOR KEY SHARE 期间,usage_logs 的当天写入、迟到写入与窗口内删除都不等待; +// 迟到写入与删除记入 build_dirty_from,同步重算脏区间后发布到今日,日桶与明细逐日一致。 +func TestGroupUsageRollupSyncDoesNotBlockUsageWritesDuringBuild(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10), (20); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-08-10 09:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-08-11 09:00:00+08'), + (3, 1, 20, 4, TIMESTAMPTZ '2026-08-12 09:00:00+08'), + (4, 1, 10, 8, TIMESTAMPTZ '2026-08-13 09:00:00+08'); + INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) + VALUES (DATE '2026-08-10', 10, 1); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2026-08-11', + retained_from = TIMESTAMPTZ '2026-08-10 09:00:00+08', + timezone_name = 'Asia/Shanghai' + WHERE id = 1; + `) + + // 让计算阶段停在清理日桶这一步:此时它已持有状态行的 FOR KEY SHARE。 + blocker, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = blocker.Rollback() }() + _, err = blocker.ExecContext(ctx, "LOCK TABLE usage_group_daily_rollups IN SHARE MODE") + require.NoError(t, err) + + repo := newDashboardAggregationRepositoryWithSQL(db) + syncDone := make(chan error, 1) + go func() { syncDone <- repo.SyncGroupUsageRollups(ctx, todayStart) }() + waitForBlockedGroupUsageRollupStatement(t, ctx, "DELETE FROM usage_group_daily_rollups") + + writeCtx, writeCancel := context.WithTimeout(ctx, 3*time.Second) + defer writeCancel() + execGroupUsageRollupSQL(t, writeCtx, db, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (5, 1, 20, 16, TIMESTAMPTZ '2026-08-12 18:00:00+08') + `) + execGroupUsageRollupSQL(t, writeCtx, db, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (6, 1, 10, 32, TIMESTAMPTZ '2026-08-14 09:00:00+08') + `) + execGroupUsageRollupSQL(t, writeCtx, db, `DELETE FROM usage_logs WHERE id = 2`) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-11", state.closedBefore) + require.Equal(t, "2026-08-14", state.buildingUntil.String) + require.Equal(t, "2026-08-11", state.buildDirtyFrom.String) + + require.NoError(t, blocker.Rollback()) + select { + case err := <-syncDone: + require.NoError(t, err) + case <-ctx.Done(): + t.Fatal("等待分组日桶同步完成超时") + } + + state = readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-14", state.closedBefore) + require.False(t, state.buildingUntil.Valid) + require.False(t, state.buildDirtyFrom.Valid) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart) + + summary := groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 41, summary[10][0], 1e-9) + require.InDelta(t, 32, summary[10][1], 1e-9) + require.InDelta(t, 8, summary[10][2], 1e-9) + require.InDelta(t, 20, summary[20][0], 1e-9) + require.InDelta(t, 0, summary[20][1], 1e-9) + require.InDelta(t, 0, summary[20][2], 1e-9) +} + +// 保留期清理按整日推进保留下界后删除:发布水位不动,过期记录的写入不触发失效, +// 窗口内的删除照常使日桶失效。 +func TestGroupUsageRollupRetentionCleanupKeepsPublishedWatermark(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10), (20); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-08-01 10:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-08-02 05:00:00+08'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-08-02 20:00:00+08'), + (4, 1, 20, 8, TIMESTAMPTZ '2026-08-05 12:00:00+08'), + (5, 1, 10, 16, TIMESTAMPTZ '2026-08-10 08:00:00+08'); + `) + + repo := newDashboardAggregationRepositoryWithSQL(db) + repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) } + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore) + + shanghai, err := time.LoadLocation("Asia/Shanghai") + require.NoError(t, err) + require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 8, 2, 12, 0, 0, 0, shanghai))) + + alignedCutoff := time.Date(2026, 8, 2, 0, 0, 0, 0, shanghai) + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-10", state.closedBefore) + require.True(t, state.expiredBefore.Equal(alignedCutoff), "expired_before=%s", state.expiredBefore) + require.True(t, state.retainedFrom.Equal(alignedCutoff), "retained_from=%s", state.retainedFrom) + require.False(t, state.buildingUntil.Valid) + + var remaining []int64 + rows, err := db.QueryContext(ctx, "SELECT id FROM usage_logs ORDER BY id") + require.NoError(t, err) + for rows.Next() { + var id int64 + require.NoError(t, rows.Scan(&id)) + remaining = append(remaining, id) + } + require.NoError(t, rows.Err()) + require.NoError(t, rows.Close()) + require.Equal(t, []int64{2, 3, 4, 5}, remaining) + + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", alignedCutoff, todayStart) + summary := groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 22, summary[10][0], 1e-9) + require.InDelta(t, 16, summary[10][1], 1e-9) + require.InDelta(t, 8, summary[20][0], 1e-9) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (6, 1, 10, 100, TIMESTAMPTZ '2026-08-01 12:00:00+08') + `) + require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore) + summary = groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 22, summary[10][0], 1e-9) + + execGroupUsageRollupSQL(t, ctx, db, `DELETE FROM usage_logs WHERE id = 4`) + require.Equal(t, "2026-08-05", readGroupUsageRollupTestState(t, ctx, db).closedBefore) + summary = groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 0, summary[20][0], 1e-9) + require.InDelta(t, 22, summary[10][0], 1e-9) +} + +func TestGroupUsageRollupTriggersIgnoreRowsBeforeExpiredFloor(t *testing.T) { + for _, partitioned := range []bool{false, true} { + name := "ordinary" + if partitioned { + name = "partitioned" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, partitioned) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) + + _, err := tx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2020-02-05 08:00:00+08'); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-03-01', + expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08' + WHERE id = 1; + DELETE FROM usage_logs WHERE id = 1; + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (3, 1, 10, 4, TIMESTAMPTZ '2020-01-20 08:00:00+08'); + UPDATE usage_logs SET actual_cost = 5 WHERE id = 3; + `) + require.NoError(t, err) + require.Equal(t, "2020-03-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + + // 把过期记录改到保留窗口内,按新日期失效。 + _, err = tx.ExecContext(ctx, ` + UPDATE usage_logs SET created_at = TIMESTAMPTZ '2020-02-20 08:00:00+08' WHERE id = 3 + `) + require.NoError(t, err) + require.Equal(t, "2020-02-20", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + + _, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 2`) + require.NoError(t, err) + require.Equal(t, "2020-02-05", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + }) + } +} + +func TestGroupUsageRollupTriggersMarkDirtyDuringBuild(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) + + _, err := tx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-01-05', + building_until = DATE '2020-01-10' + WHERE id = 1; + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-12 08:00:00+08'); + `) + require.NoError(t, err) + state := readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-05", state.closedBefore) + require.False(t, state.buildDirtyFrom.Valid) + + _, err = tx.ExecContext(ctx, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08') + `) + require.NoError(t, err) + state = readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-05", state.closedBefore) + require.Equal(t, "2020-01-07", state.buildDirtyFrom.String) + + _, err = tx.ExecContext(ctx, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (3, 1, 10, 1, TIMESTAMPTZ '2020-01-03 08:00:00+08') + `) + require.NoError(t, err) + state = readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-03", state.closedBefore) + require.Equal(t, "2020-01-03", state.buildDirtyFrom.String) + + _, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 1`) + require.NoError(t, err) + state = readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-03", state.buildDirtyFrom.String) +} + +// 计算阶段对状态行只持 FOR KEY SHARE:迟到写入与窗口内删除都不等待它。 +func TestGroupUsageRollupBuildKeyShareDoesNotBlockLateWrites(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + seedTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + _, err := seedTx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-08 08:00:00+08'); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-01-05', + building_until = DATE '2020-01-10' + WHERE id = 1; + `) + require.NoError(t, err) + require.NoError(t, seedTx.Commit()) + + buildTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = buildTx.Rollback() }() + var stateID int16 + require.NoError(t, buildTx.QueryRowContext(ctx, ` + SELECT id FROM usage_group_rollup_state WHERE id = 1 FOR KEY SHARE + `).Scan(&stateID)) + + for _, statement := range []string{ + `INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08')`, + `DELETE FROM usage_logs WHERE id = 1`, + } { + writeTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, writeTx, "Asia/Shanghai")) + var writePID int + require.NoError(t, writeTx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&writePID)) + result := make(chan error, 1) + go func(statement string) { + _, execErr := writeTx.ExecContext(ctx, statement) + result <- execErr + }(statement) + blocked, err := waitForGroupUsageRollupStateLock(ctx, writePID, result) + require.NoError(t, err) + require.False(t, blocked, "计算阶段不得阻塞: %s", statement) + require.NoError(t, writeTx.Commit()) + } + + require.NoError(t, buildTx.Commit()) + var dirtyFrom string + require.NoError(t, integrationDB.QueryRowContext(ctx, fmt.Sprintf( + "SELECT build_dirty_from::text FROM %s.usage_group_rollup_state WHERE id = 1", + pq.QuoteIdentifier(schema), + )).Scan(&dirtyFrom)) + require.Equal(t, "2020-01-07", dirtyFrom) +} + +func TestGroupUsageRollupSyncSkipsWhileAnotherBuildHoldsLock(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + holder, err := integrationDB.Conn(ctx) + require.NoError(t, err) + defer func() { _ = holder.Close() }() + var locked bool + require.NoError(t, holder.QueryRowContext(ctx, groupUsageRollupBuildLockSQL).Scan(&locked)) + require.True(t, locked) + defer func() { _, _ = holder.ExecContext(context.Background(), groupUsageRollupBuildUnlockSQL) }() + + repo := newDashboardAggregationRepositoryWithSQL(db) + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "1970-01-01", state.closedBefore) + require.False(t, state.buildingUntil.Valid) +} + +// 上一次重建在登记之后中断:下一次同步覆盖遗留登记并发布到今日。 +func TestGroupUsageRollupSyncRecoversFromInterruptedBuild(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-08-11 09:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-08-12 09:00:00+08'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-08-13 09:00:00+08'); + INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) VALUES + (DATE '2026-08-11', 10, 1), + (DATE '2026-08-12', 10, 999); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2026-08-12', + retained_from = TIMESTAMPTZ '2026-08-11 09:00:00+08', + timezone_name = 'Asia/Shanghai', + building_until = DATE '2026-08-14', + build_dirty_from = DATE '2026-08-13' + WHERE id = 1; + `) + + repo := newDashboardAggregationRepositoryWithSQL(db) + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-14", state.closedBefore) + require.False(t, state.buildingUntil.Valid) + require.False(t, state.buildDirtyFrom.Valid) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart) +} + +type groupUsageRollupTestState struct { + closedBefore string + retainedFrom time.Time + expiredBefore time.Time + buildingUntil sql.NullString + buildDirtyFrom sql.NullString +} + +const groupUsageRollupTestStateQuery = ` + SELECT closed_before::text, retained_from, expired_before, building_until::text, build_dirty_from::text + FROM usage_group_rollup_state + WHERE id = 1 +` + +func readGroupUsageRollupTestState(t *testing.T, ctx context.Context, q sqlQueryer) groupUsageRollupTestState { + t.Helper() + var state groupUsageRollupTestState + require.NoError(t, scanSingleRow(ctx, q, groupUsageRollupTestStateQuery, nil, + &state.closedBefore, &state.retainedFrom, &state.expiredBefore, &state.buildingUntil, &state.buildDirtyFrom)) + return state +} + +func readGroupUsageRollupTestStateTx(t *testing.T, ctx context.Context, tx *sql.Tx) groupUsageRollupTestState { + t.Helper() + return readGroupUsageRollupTestState(t, ctx, tx) +} + +// openGroupUsageRollupSchemaDB 打开一个 search_path 指向 schema 的连接池,供仓储以 *sql.DB 方式运行。 +func openGroupUsageRollupSchemaDB(t *testing.T, schema, timezoneName string) *sql.DB { + t.Helper() + dsn, err := url.Parse(integrationDSN) + require.NoError(t, err) + query := dsn.Query() + query.Set("search_path", schema) + query.Set("TimeZone", timezoneName) + dsn.RawQuery = query.Encode() + db, err := sql.Open("postgres", dsn.String()) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + require.NoError(t, db.PingContext(context.Background())) + return db +} + +func execGroupUsageRollupSQL(t *testing.T, ctx context.Context, db *sql.DB, query string) { + t.Helper() + _, err := db.ExecContext(ctx, query) + require.NoError(t, err) +} + +// waitForBlockedGroupUsageRollupStatement 等待某个后端在执行包含 fragment 的语句时进入锁等待。 +func waitForBlockedGroupUsageRollupStatement(t *testing.T, ctx context.Context, fragment string) { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + var blocked bool + require.NoError(t, integrationDB.QueryRowContext(ctx, ` + SELECT EXISTS ( + SELECT 1 + FROM pg_stat_activity + WHERE wait_event_type = 'Lock' + AND position($1 in query) > 0 + ) + `, fragment).Scan(&blocked)) + if blocked { + return + } + select { + case <-ticker.C: + case <-ctx.Done(): + t.Fatalf("等待语句进入锁等待超时: %s", fragment) + } + } +} + +// requireGroupUsageRollupsMatchUsageLogs 断言 [retainedFrom 所在日, todayStart) 的日桶与 usage_logs 明细逐日一致。 +func requireGroupUsageRollupsMatchUsageLogs(t *testing.T, ctx context.Context, db *sql.DB, timezoneName string, retainedFrom, todayStart time.Time) { + t.Helper() + expected := collectGroupUsageRollupBuckets(t, ctx, db, ` + SELECT (created_at AT TIME ZONE $3::text)::date::text, group_id, SUM(actual_cost)::float8 + FROM usage_logs + WHERE group_id IS NOT NULL + AND created_at >= $1 + AND created_at < $2 + GROUP BY 1, 2 + `, retainedFrom, todayStart, timezoneName) + actual := collectGroupUsageRollupBuckets(t, ctx, db, ` + SELECT bucket_date::text, group_id, actual_cost::float8 + FROM usage_group_daily_rollups + WHERE bucket_date >= ($1::timestamptz AT TIME ZONE $3::text)::date + AND bucket_date < ($2::timestamptz AT TIME ZONE $3::text)::date + `, retainedFrom, todayStart, timezoneName) + require.Equal(t, expected, actual) +} + +func collectGroupUsageRollupBuckets(t *testing.T, ctx context.Context, db *sql.DB, query string, args ...any) map[string]float64 { + t.Helper() + rows, err := db.QueryContext(ctx, query, args...) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + buckets := make(map[string]float64) + for rows.Next() { + var bucketDate string + var groupID int64 + var cost float64 + require.NoError(t, rows.Scan(&bucketDate, &groupID, &cost)) + buckets[fmt.Sprintf("%s/%d", bucketDate, groupID)] = cost + } + require.NoError(t, rows.Err()) + return buckets +} + +// groupUsageSummaryByGroup 返回 group_id → [total, today, yesterday]。 +func groupUsageSummaryByGroup(t *testing.T, ctx context.Context, db *sql.DB, todayStart time.Time) map[int64][3]float64 { + t.Helper() + result, err := newUsageLogRepositoryWithSQL(nil, db).GetAllGroupUsageSummary(ctx, todayStart) + require.NoError(t, err) + summary := make(map[int64][3]float64, len(result)) + for _, row := range result { + summary[row.GroupID] = [3]float64{row.TotalCost, row.TodayCost, row.YesterdayCost} + } + return summary +} + +// 重建进行中的大批量删除:脏日期已覆盖的行不写状态行,状态行在事务内只更新一次。 +func TestGroupUsageRollupBulkDeleteDuringBuildWritesStateOnce(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) + + _, err := tx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + SELECT n, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08' + n * INTERVAL '1 second' + FROM generate_series(1, 2000) AS n; + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-01-10', + building_until = DATE '2020-02-01' + WHERE id = 1; + `) + require.NoError(t, err) + + var updatesBefore int64 + require.NoError(t, tx.QueryRowContext(ctx, ` + SELECT n_tup_upd FROM pg_stat_xact_user_tables + WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state' + `).Scan(&updatesBefore)) + + _, err = tx.ExecContext(ctx, `DELETE FROM usage_logs`) + require.NoError(t, err) + + var updatesAfter int64 + require.NoError(t, tx.QueryRowContext(ctx, ` + SELECT n_tup_upd FROM pg_stat_xact_user_tables + WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state' + `).Scan(&updatesAfter)) + require.Equal(t, int64(1), updatesAfter-updatesBefore) + + state := readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-10", state.closedBefore) + require.Equal(t, "2020-01-15", state.buildDirtyFrom.String) +} + +// 应用侧失效的起点早于保留下界时,从保留下界所在日开始失效。 +func TestGroupUsageRollupInvalidateAtStartsFromExpiredFloor(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + + _, err := tx.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-03-01', + expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08' + WHERE id = 1; + SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-01-10 08:00:00+08', 'Asia/Shanghai'); + `) + require.NoError(t, err) + require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + + _, err = tx.ExecContext(ctx, ` + SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-02-10 08:00:00+08', 'Asia/Shanghai') + `) + require.NoError(t, err) + require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) +} + +// 夏令时在零点跳变的日期(America/Santiago 2026-09-06 没有 00:00):从该日续建时不覆盖前一天的日桶。 +func TestGroupUsageRollupSyncKeepsPreviousDayBucketAcrossMidnightDSTGap(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "America/Santiago") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "America/Santiago") + santiago, err := time.LoadLocation("America/Santiago") + require.NoError(t, err) + todayStart := time.Date(2026, 9, 8, 0, 0, 0, 0, santiago) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-09-06 02:30:00+00'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-09-06 03:30:00+00'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-09-06 05:00:00+00'), + (4, 1, 10, 8, TIMESTAMPTZ '2026-09-07 13:00:00+00'); + INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) + VALUES (DATE '2026-09-05', 10, 3); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2026-09-06', + retained_from = TIMESTAMPTZ '2026-09-06 02:30:00+00', + timezone_name = 'America/Santiago' + WHERE id = 1; + `) + + repo := newDashboardAggregationRepositoryWithSQL(db) + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-09-08", state.closedBefore) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "America/Santiago", state.retainedFrom, todayStart) + var previousDay float64 + require.NoError(t, db.QueryRowContext(ctx, ` + SELECT actual_cost::float8 FROM usage_group_daily_rollups + WHERE bucket_date = DATE '2026-09-05' AND group_id = 10 + `).Scan(&previousDay)) + require.InDelta(t, 3, previousDay, 1e-9) +} + +// 有长读者持有 usage_logs 的 ACCESS SHARE 时,删除分区在锁等待超时后跳过; +// 过期记录由按行删除清理,清理整体成功,分组日汇总保持一致。 +func TestGroupUsageRollupRetentionCleanupSkipsPartitionDropOnLockTimeout(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, true) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + CREATE TABLE usage_logs_202605 PARTITION OF usage_logs + FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-05-10 10:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-07-20 10:00:00+08'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-08-05 10:00:00+08'); + `) + repo := newDashboardAggregationRepositoryWithSQL(db) + repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) } + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + + reader, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = reader.Rollback() }() + var count int + require.NoError(t, reader.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count)) + require.Equal(t, 3, count) + + shanghai, err := time.LoadLocation("Asia/Shanghai") + require.NoError(t, err) + require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 7, 1, 0, 0, 0, 0, shanghai))) + require.NoError(t, reader.Rollback()) + + var partitionExists bool + require.NoError(t, db.QueryRowContext(ctx, "SELECT to_regclass('usage_logs_202605') IS NOT NULL").Scan(&partitionExists)) + require.True(t, partitionExists) + require.NoError(t, db.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count)) + require.Equal(t, 2, count) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-10", state.closedBefore) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart) + summary := groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 6, summary[10][0], 1e-9) +} diff --git a/backend/internal/repository/group_usage_rollup_trigger_integration_test.go b/backend/internal/repository/group_usage_rollup_trigger_integration_test.go index 32016e3c0a..c145bef4eb 100644 --- a/backend/internal/repository/group_usage_rollup_trigger_integration_test.go +++ b/backend/internal/repository/group_usage_rollup_trigger_integration_test.go @@ -451,6 +451,7 @@ func createGroupUsageRollupTriggerTestSchema(t *testing.T, ctx context.Context, for _, migrationName := range []string{ "222_group_usage_daily_rollups.sql", "223_group_usage_rollup_timezone.sql", + "251_group_usage_rollup_nonblocking_build.sql", } { migrationSQL, readErr := migrations.FS.ReadFile(migrationName) require.NoError(t, readErr) diff --git a/backend/internal/repository/integration_harness_test.go b/backend/internal/repository/integration_harness_test.go index 46f18598f2..d33b229449 100644 --- a/backend/internal/repository/integration_harness_test.go +++ b/backend/internal/repository/integration_harness_test.go @@ -36,6 +36,7 @@ const ( var ( integrationDB *sql.DB + integrationDSN string integrationEntClient *dbent.Client integrationRedis *redisclient.Client @@ -91,6 +92,7 @@ func TestMain(m *testing.M) { os.Exit(1) } + integrationDSN = dsn integrationDB, err = openSQLWithRetry(ctx, dsn, 30*time.Second) if err != nil { log.Printf("failed to open sql db: %v", err) diff --git a/backend/internal/repository/usage_cleanup_repo.go b/backend/internal/repository/usage_cleanup_repo.go index f8aa67477f..a9b184a18e 100644 --- a/backend/internal/repository/usage_cleanup_repo.go +++ b/backend/internal/repository/usage_cleanup_repo.go @@ -291,9 +291,7 @@ func (r *usageCleanupRepository) DeleteUsageLogsBatch(ctx context.Context, filte return 0, fmt.Errorf("cleanup filters missing time range") } args = append(args, limit) - if db, ok := r.sql.(*sql.DB); ok { - return r.deleteUsageLogsBatchWithRollupInvalidation(ctx, db, whereClause, args) - } + // usage_logs 的行级触发器按被删记录的日期使分组日桶失效。 query := fmt.Sprintf(` WITH target AS ( SELECT id @@ -323,68 +321,6 @@ func (r *usageCleanupRepository) DeleteUsageLogsBatch(ctx context.Context, filte return deleted, nil } -func (r *usageCleanupRepository) deleteUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, whereClause string, args []any) (int64, error) { - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return 0, err - } - rollback := func(err error) (int64, error) { - _ = tx.Rollback() - return 0, err - } - - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - return rollback(err) - } - query := fmt.Sprintf(` - WITH target AS ( - SELECT id - FROM usage_logs - WHERE %s - ORDER BY created_at ASC, id ASC - LIMIT $%d - ) - DELETE FROM usage_logs - WHERE id IN (SELECT id FROM target) - RETURNING created_at - `, whereClause, len(args)) - rows, err := tx.QueryContext(ctx, query, args...) - if err != nil { - return rollback(err) - } - - var deleted int64 - var earliestDeletedAt time.Time - for rows.Next() { - var deletedAt time.Time - if err := rows.Scan(&deletedAt); err != nil { - _ = rows.Close() - return rollback(err) - } - deleted++ - if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) { - earliestDeletedAt = deletedAt - } - } - if err := rows.Err(); err != nil { - _ = rows.Close() - return rollback(err) - } - if err := rows.Close(); err != nil { - return rollback(err) - } - - if deleted > 0 { - if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil { - return rollback(err) - } - } - if err := tx.Commit(); err != nil { - return 0, err - } - return deleted, nil -} - func buildUsageCleanupWhere(filters service.UsageCleanupFilters) (string, []any) { conditions := make([]string, 0, 8) args := make([]any, 0, 8) diff --git a/backend/internal/repository/usage_cleanup_repo_test.go b/backend/internal/repository/usage_cleanup_repo_test.go index b147d03a4f..4b0034ca0d 100644 --- a/backend/internal/repository/usage_cleanup_repo_test.go +++ b/backend/internal/repository/usage_cleanup_repo_test.go @@ -418,16 +418,9 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatch(t *testing.T) { Model: &model, } - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) mock.ExpectQuery("DELETE FROM usage_logs"). WithArgs(start, end, userID, "gpt-4", 2). WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(start.Add(time.Hour)).AddRow(start.Add(2 * time.Hour))) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(start.Add(time.Hour), "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() deleted, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 2) require.NoError(t, err) @@ -435,29 +428,22 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatch(t *testing.T) { require.NoError(t, mock.ExpectationsWereMet()) } -func TestUsageCleanupRepositoryDeleteUsageLogsBatchAtomicallyInvalidatesGroupRollups(t *testing.T) { +// 分组日桶失效由 usage_logs 的行级触发器完成,删除批次不显式锁定汇总状态行, +// 因而不与 usage_logs 写入串行。 +func TestUsageCleanupRepositoryDeleteUsageLogsBatchDoesNotLockGroupRollupState(t *testing.T) { setUsageCleanupRollupTestTimezone(t) db, mock := newSQLMock(t) repo := &usageCleanupRepository{sql: db} start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC) end := start.Add(24 * time.Hour) - firstDeletedAt := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) - secondDeletedAt := firstDeletedAt.Add(time.Hour) filters := service.UsageCleanupFilters{StartTime: start, EndTime: end} - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`). + mock.ExpectQuery(`(?s)WITH target AS.*DELETE FROM usage_logs.*RETURNING created_at`). WithArgs(start, end, 2). WillReturnRows(sqlmock.NewRows([]string{"created_at"}). - AddRow(firstDeletedAt). - AddRow(secondDeletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(firstDeletedAt, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() + AddRow(start.Add(3 * time.Hour)). + AddRow(start.Add(4 * time.Hour))) deleted, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 2) require.NoError(t, err) @@ -465,32 +451,6 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatchAtomicallyInvalidatesGroupRol require.NoError(t, mock.ExpectationsWereMet()) } -func TestUsageCleanupRepositoryDeleteUsageLogsBatchRollsBackWhenInvalidationFails(t *testing.T) { - setUsageCleanupRollupTestTimezone(t) - db, mock := newSQLMock(t) - repo := &usageCleanupRepository{sql: db} - - start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC) - end := start.Add(24 * time.Hour) - deletedAt := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) - filters := service.UsageCleanupFilters{StartTime: start, EndTime: end} - - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`). - WithArgs(start, end, 1). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(deletedAt, "Asia/Shanghai"). - WillReturnError(sql.ErrConnDone) - mock.ExpectRollback() - - _, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 1) - require.ErrorIs(t, err, sql.ErrConnDone) - require.NoError(t, mock.ExpectationsWereMet()) -} - func TestUsageCleanupRepositoryDeleteUsageLogsBatchQueryError(t *testing.T) { db, mock := newSQLMock(t) repo := &usageCleanupRepository{sql: db} @@ -499,13 +459,9 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatchQueryError(t *testing.T) { end := start.Add(24 * time.Hour) filters := service.UsageCleanupFilters{StartTime: start, EndTime: end} - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) mock.ExpectQuery("DELETE FROM usage_logs"). WithArgs(start, end, 5). WillReturnError(sql.ErrConnDone) - mock.ExpectRollback() _, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 5) require.Error(t, err) diff --git a/backend/internal/repository/usage_log_repo_group_summary_test.go b/backend/internal/repository/usage_log_repo_group_summary_test.go index 676a252ab8..986616736e 100644 --- a/backend/internal/repository/usage_log_repo_group_summary_test.go +++ b/backend/internal/repository/usage_log_repo_group_summary_test.go @@ -20,8 +20,8 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryUsesRollupTail(t *testing.T) { // 水位有效:closed_before = 2026-03-07(≤ today),时区与配置一致。 mock.ExpectQuery(`(?s)COUNT\(\*\).*usage_group_rollup_state.*WHERE id = 1`). - WillReturnRows(sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York")) + WillReturnRows(sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York", time.Unix(0, 0).UTC())) // 尾段起点必须以参数形式进 WHERE —— 这正是把 usage_logs 全表扫换回 // idx_usage_logs_created_at 索引扫的那一步。 @@ -61,18 +61,18 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryFallsBackWhenWatermarkInvalid( }{ { name: "水位行缺失", - rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(0, nil, nil, nil), + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(0, nil, nil, nil, nil), }, { name: "时区与当前配置不一致", - rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "Asia/Shanghai"), + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "Asia/Shanghai", time.Unix(0, 0).UTC()), }, { name: "水位位于未来", - rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(1, "2026-03-10", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York"), + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-10", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York", time.Unix(0, 0).UTC()), }, } @@ -94,3 +94,66 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryFallsBackWhenWatermarkInvalid( }) } } + +// 尾段不早于保留下界:水位落后于保留下界时(例如清理已推进下界而重建尚未完成), +// 尚未删除的过期记录也不计入。 +func TestUsageLogRepositoryGetAllGroupUsageSummaryTailStartsAtExpiredBefore(t *testing.T) { + todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) + yesterdayStart := time.Date(2026, 3, 8, 5, 0, 0, 0, time.UTC) + expiredBefore := time.Date(2026, 2, 10, 5, 0, 0, 0, time.UTC) + + cases := []struct { + name string + rows *sqlmock.Rows + valid bool + retained string + closed string + tailStart time.Time + }{ + { + name: "水位有效但早于保留下界", + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-02-01", expiredBefore, "America/New_York", expiredBefore), + valid: true, + retained: "2026-02-10", + closed: "2026-02-01", + tailStart: expiredBefore, + }, + { + name: "retained_from 早于保留下界", + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", time.Date(2026, 1, 20, 5, 0, 0, 0, time.UTC), "America/New_York", expiredBefore), + valid: true, + retained: "2026-02-10", + closed: "2026-03-07", + tailStart: time.Date(2026, 3, 7, 5, 0, 0, 0, time.UTC), + }, + { + name: "水位无效", + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", expiredBefore, "Asia/Shanghai", expiredBefore), + valid: false, + retained: "1970-01-01", + closed: "1970-01-01", + tailStart: expiredBefore, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + db, mock := newSQLMock(t) + repo := newUsageLogRepositoryWithSQL(nil, db) + useGroupUsageRepositoryTestTimezone(t, "America/New_York") + + mock.ExpectQuery(`(?s)COUNT\(\*\).*MAX\(expired_before\).*usage_group_rollup_state.*WHERE id = 1`). + WillReturnRows(tc.rows) + mock.ExpectQuery(`(?s)usage_group_daily_rollups.*FROM usage_logs ul\s+WHERE ul\.created_at >= \$7`). + WithArgs(todayStart, yesterdayStart, "2026-03-08", tc.valid, tc.retained, tc.closed, tc.tailStart). + WillReturnRows(sqlmock.NewRows([]string{"group_id", "total_cost", "today_cost", "yesterday_cost"})) + + _, err := repo.GetAllGroupUsageSummary(context.Background(), todayStart) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/service/custom_group_usage_rollup.go b/backend/internal/service/custom_group_usage_rollup.go index d14dc9bfd9..79123c8be0 100644 --- a/backend/internal/service/custom_group_usage_rollup.go +++ b/backend/internal/service/custom_group_usage_rollup.go @@ -21,12 +21,14 @@ func GroupUsageTimezoneName() string { // GroupUsageTodayStart 返回指定时刻在服务端配置时区内的自然日 UTC 起点。 func GroupUsageTodayStart(at time.Time) time.Time { - return appTimezone.StartOfDay(at).UTC() + year, month, day := at.In(appTimezone.Location()).Date() + return groupUsageDayStart(year, month, day).UTC() } // GroupUsageYesterdayStart 返回指定时刻前一个本地日历日的 UTC 起点。 func GroupUsageYesterdayStart(at time.Time) time.Time { - return appTimezone.StartOfDay(at).AddDate(0, 0, -1).UTC() + // 任一本地日至少 22 小时,当日起点前 12 小时必落在前一个日历日内。 + return GroupUsageTodayStart(GroupUsageTodayStart(at).Add(-12 * time.Hour)) } // GroupUsageDate 返回指定时刻在服务端配置时区内的日期。 @@ -34,7 +36,44 @@ func GroupUsageDate(at time.Time) string { return at.In(appTimezone.Location()).Format(groupUsageDateFormat) } -// ParseGroupUsageDate 解析服务端配置时区内的日期并返回其零点。 +// ParseGroupUsageDate 解析服务端配置时区内的日期并返回该日期的起点。 func ParseGroupUsageDate(value string) (time.Time, error) { - return appTimezone.ParseInLocation(groupUsageDateFormat, value) + date, err := time.Parse(groupUsageDateFormat, value) + if err != nil { + return time.Time{}, err + } + year, month, day := date.Date() + return groupUsageDayStart(year, month, day), nil +} + +// groupUsageDayStart 返回本地日期 year-month-day 的第一个时刻(服务端配置时区)。 +// 夏令时在零点跳变的日期,00:00 可能不存在或出现两次,此时返回该日期实际开始的时刻。 +func groupUsageDayStart(year int, month time.Month, day int) time.Time { + loc := appTimezone.Location() + target := groupUsageDateOrdinal(year, month, day) + start := time.Date(year, month, day, 0, 0, 0, 0, loc) + if localGroupUsageDateOrdinal(start) == target && localGroupUsageDateOrdinal(start.Add(-time.Nanosecond)) < target { + return start + } + // 在 [前一日正午, 当日正午] 内二分出本地日期首次到达目标日期的时刻。 + low := time.Date(year, month, day-1, 12, 0, 0, 0, loc) + high := time.Date(year, month, day, 12, 0, 0, 0, loc) + for high.Sub(low) > time.Nanosecond { + mid := low.Add(high.Sub(low) / 2) + if localGroupUsageDateOrdinal(mid) >= target { + high = mid + } else { + low = mid + } + } + return high +} + +func localGroupUsageDateOrdinal(at time.Time) int { + year, month, day := at.In(appTimezone.Location()).Date() + return groupUsageDateOrdinal(year, month, day) +} + +func groupUsageDateOrdinal(year int, month time.Month, day int) int { + return year*10000 + int(month)*100 + day } diff --git a/backend/internal/service/dashboard_aggregation_service.go b/backend/internal/service/dashboard_aggregation_service.go index c85dec07a3..82b0a94889 100644 --- a/backend/internal/service/dashboard_aggregation_service.go +++ b/backend/internal/service/dashboard_aggregation_service.go @@ -373,13 +373,18 @@ func (s *DashboardAggregationService) maybeCleanupRetention(ctx context.Context, } hourlyCutoff := now.AddDate(0, 0, -s.cfg.Retention.HourlyDays) dailyCutoff := now.AddDate(0, 0, -s.cfg.Retention.DailyDays) - usageCutoff := now.AddDate(0, 0, -usageDays) + // usage_logs 按服务端配置时区整日保留,与分组日桶的日界对齐。 + usageCutoff := GroupUsageTodayStart(now.AddDate(0, 0, -usageDays)) dedupDays := s.cfg.Retention.UsageBillingDedupDays if dedupDays <= 0 { dedupDays = 365 } dedupDays = max(dedupDays, usageDays) + // 计费去重记录的保留不短于 usage_logs。 dedupCutoff := now.AddDate(0, 0, -dedupDays) + if usageDays > 0 && dedupCutoff.After(usageCutoff) { + dedupCutoff = usageCutoff + } var aggErr, usageErr, dedupErr error if s.cfg.Enabled { diff --git a/backend/internal/service/request_log_retention_test.go b/backend/internal/service/request_log_retention_test.go index 4cc8955f79..a41c5bd2c5 100644 --- a/backend/internal/service/request_log_retention_test.go +++ b/backend/internal/service/request_log_retention_test.go @@ -9,6 +9,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" "github.com/stretchr/testify/require" ) @@ -40,8 +41,13 @@ func TestRequestLogRetention_RuntimePolicy(t *testing.T) { svc.maybeCleanupRetention(context.Background(), now) if tt.wantCleanup { require.Equal(t, 1, repo.cleanupUsageCalls) - require.Equal(t, now.AddDate(0, 0, -tt.wantDays), repo.cleanupUsageCutoff) - require.Equal(t, now.AddDate(0, 0, -max(365, tt.wantDays)), repo.cleanupDedupCutoff) + wantUsageCutoff := GroupUsageTodayStart(now.AddDate(0, 0, -tt.wantDays)) + wantDedupCutoff := now.AddDate(0, 0, -max(365, tt.wantDays)) + if wantDedupCutoff.After(wantUsageCutoff) { + wantDedupCutoff = wantUsageCutoff + } + require.Equal(t, wantUsageCutoff, repo.cleanupUsageCutoff) + require.Equal(t, wantDedupCutoff, repo.cleanupDedupCutoff) } else { require.Zero(t, repo.cleanupUsageCalls) require.Zero(t, repo.cleanupDedupCalls) @@ -53,7 +59,7 @@ func TestRequestLogRetention_RuntimePolicy(t *testing.T) { settings.values[SettingKeyOpsRuntimeLogConfig] = `{"request_retention_days":180}` next := now.Add(dashboardAggregationRetentionInterval) svc.maybeCleanupRetention(context.Background(), next) - require.Equal(t, next.AddDate(0, 0, -180), repo.cleanupUsageCutoff) + require.Equal(t, GroupUsageTodayStart(next.AddDate(0, 0, -180)), repo.cleanupUsageCutoff) }) } } @@ -107,3 +113,70 @@ func TestRuntimeLogConfig_RequestRetentionCompatibility(t *testing.T) { require.NoError(t, err) require.Equal(t, 90, *reset.RequestRetentionDays) } + +func TestRequestLogRetention_CutoffAlignsToConfiguredDayStart(t *testing.T) { + previous := timezone.Name() + require.NoError(t, timezone.Init("Asia/Shanghai")) + t.Cleanup(func() { require.NoError(t, timezone.Init(previous)) }) + + for _, tt := range []struct { + name string + dedupDays int + wantDedup time.Time + }{ + // 2026-09-15 20:00 +08 往前 90 天是 2026-06-17 20:00 +08,对齐到 2026-06-17 00:00 +08。 + {"dedup longer than usage", 365, time.Date(2025, 9, 15, 12, 0, 0, 0, time.UTC)}, + {"dedup equal to usage keeps whole days", 90, time.Date(2026, 6, 16, 16, 0, 0, 0, time.UTC)}, + } { + t.Run(tt.name, func(t *testing.T) { + repo := &dashboardAggregationRepoTestStub{} + svc := NewDashboardAggregationService(repo, nil, &config.Config{DashboardAgg: config.DashboardAggregationConfig{ + Enabled: true, + Retention: config.DashboardAggregationRetentionConfig{UsageLogsDays: 90, UsageBillingDedupDays: tt.dedupDays, HourlyDays: 180, DailyDays: 730}, + }}) + now := time.Date(2026, 9, 15, 12, 0, 0, 0, time.UTC) + svc.maybeCleanupRetention(context.Background(), now) + + require.Equal(t, time.Date(2026, 6, 16, 16, 0, 0, 0, time.UTC), repo.cleanupUsageCutoff) + require.Equal(t, tt.wantDedup, repo.cleanupDedupCutoff) + }) + } +} + +// 夏令时在零点跳变的日期没有 00:00:日界取该日期实际开始的时刻,而不是前一天的 23:00。 +func TestGroupUsageDayBoundariesSkipMidnightDSTGap(t *testing.T) { + previous := timezone.Name() + require.NoError(t, timezone.Init("America/Santiago")) + t.Cleanup(func() { require.NoError(t, timezone.Init(previous)) }) + loc := timezone.Location() + + noon := time.Date(2026, 9, 6, 12, 0, 0, 0, loc) + start := GroupUsageTodayStart(noon) + require.Equal(t, "2026-09-06", GroupUsageDate(start)) + require.Equal(t, "2026-09-05", GroupUsageDate(start.Add(-time.Nanosecond))) + + parsed, err := ParseGroupUsageDate("2026-09-06") + require.NoError(t, err) + require.True(t, parsed.Equal(start), "parsed=%s start=%s", parsed, start) + + nextNoon := time.Date(2026, 9, 7, 12, 0, 0, 0, loc) + require.True(t, GroupUsageYesterdayStart(nextNoon).Equal(start)) + + // 普通日期仍是本地零点。 + regular, err := ParseGroupUsageDate("2026-09-08") + require.NoError(t, err) + require.True(t, regular.Equal(time.Date(2026, 9, 8, 0, 0, 0, 0, loc))) +} + +// 零点出现两次的日期(Asia/Gaza 2020-10-24 在 01:00 回拨到 00:00):日界取第一次出现的 00:00。 +func TestGroupUsageDayBoundariesUseFirstOfRepeatedMidnight(t *testing.T) { + previous := timezone.Name() + require.NoError(t, timezone.Init("Asia/Gaza")) + t.Cleanup(func() { require.NoError(t, timezone.Init(previous)) }) + + start, err := ParseGroupUsageDate("2020-10-24") + require.NoError(t, err) + require.Equal(t, "2020-10-24", GroupUsageDate(start)) + require.Equal(t, "2020-10-23", GroupUsageDate(start.Add(-time.Nanosecond))) + require.True(t, GroupUsageTodayStart(start.Add(90*time.Minute)).Equal(start)) +} diff --git a/backend/migrations/251_group_usage_rollup_nonblocking_build.sql b/backend/migrations/251_group_usage_rollup_nonblocking_build.sql new file mode 100644 index 0000000000..279c95b201 --- /dev/null +++ b/backend/migrations/251_group_usage_rollup_nonblocking_build.sql @@ -0,0 +1,159 @@ +-- /admin/groups 分组日汇总的过期下界与重建登记。 +-- expired_before 之前的 usage_logs 已超出保留期,不属于任何可读日桶,其变更不触发失效。 +-- 重建期间登记 building_until;落在该日期之前的源记录变更记入 build_dirty_from, +-- 发布时水位不越过 build_dirty_from,因此重建计算阶段无需排斥 usage_logs 写入。 + +SET LOCAL lock_timeout = '5s'; + +ALTER TABLE usage_group_rollup_state + ADD COLUMN IF NOT EXISTS expired_before TIMESTAMPTZ NOT NULL DEFAULT TIMESTAMPTZ '1970-01-01 00:00:00+00', + ADD COLUMN IF NOT EXISTS building_until DATE, + ADD COLUMN IF NOT EXISTS build_dirty_from DATE; + +COMMENT ON COLUMN usage_group_rollup_state.expired_before IS '早于该时刻的 usage_logs 已超出保留期,不计入分组日汇总,也不触发失效。'; +COMMENT ON COLUMN usage_group_rollup_state.building_until IS '进行中重建的目标日期(排他上界);没有重建时为 NULL。'; +COMMENT ON COLUMN usage_group_rollup_state.build_dirty_from IS '重建期间源记录发生变化的最早日期;发布水位不越过该日期。'; + +-- 按受影响日期后退发布水位,并在重建进行中记录脏日期;水位与脏日期都已不晚于该日期时不写状态行。 +-- 调用方必须已对状态行持有 FOR KEY SHARE 或更强的行锁:重建的登记与发布持有 FOR UPDATE, +-- 由此保证每次源记录变更要么先于登记提交、被重建快照看到,要么看到登记并记入脏日期。 +CREATE OR REPLACE FUNCTION apply_group_usage_rollup_invalidation(affected_date DATE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +BEGIN + UPDATE usage_group_rollup_state + SET closed_before = LEAST(closed_before, affected_date), + build_dirty_from = CASE + WHEN building_until > affected_date THEN LEAST(build_dirty_from, affected_date) + ELSE build_dirty_from + END, + updated_at = NOW() + WHERE id = 1 + AND ( + closed_before > affected_date + OR ( + building_until > affected_date + AND (build_dirty_from IS NULL OR build_dirty_from > affected_date) + ) + ); +END; +$$; + +-- 供应用侧调用:使 affected_at 在 bucket_timezone 中的日期及之后的日桶失效; +-- 早于 expired_before 的部分不属于任何可读日桶,失效从 expired_before 起算。 +CREATE OR REPLACE FUNCTION invalidate_group_usage_rollups_at(affected_at TIMESTAMPTZ, bucket_timezone TEXT) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + state_expired_before TIMESTAMPTZ; +BEGIN + SELECT expired_before + INTO state_expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE; + + IF NOT FOUND OR affected_at IS NULL THEN + RETURN; + END IF; + + PERFORM apply_group_usage_rollup_invalidation( + (GREATEST(affected_at, state_expired_before) AT TIME ZONE bucket_timezone)::date + ); +END; +$$; + +-- DELETE/UPDATE 行级触发器。FOR KEY SHARE 与 usage_logs 写入及其他失效互相兼容,只与重建的登记、发布串行。 +CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + configured_timezone TEXT := current_setting('TimeZone'); + old_date DATE; + new_date DATE; + affected_date DATE; + state_closed_before DATE; + state_building_until DATE; + state_build_dirty_from DATE; + state_expired_before TIMESTAMPTZ; +BEGIN + SELECT closed_before, building_until, build_dirty_from, expired_before + INTO state_closed_before, state_building_until, state_build_dirty_from, state_expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE; + + IF FOUND THEN + IF OLD.group_id IS NOT NULL AND OLD.created_at >= state_expired_before THEN + old_date := (OLD.created_at AT TIME ZONE configured_timezone)::date; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW.group_id IS NOT NULL AND NEW.created_at >= state_expired_before THEN + new_date := (NEW.created_at AT TIME ZONE configured_timezone)::date; + END IF; + END IF; + + affected_date := LEAST(old_date, new_date); + IF state_closed_before > affected_date + OR ( + state_building_until > affected_date + AND (state_build_dirty_from IS NULL OR state_build_dirty_from > affected_date) + ) THEN + PERFORM apply_group_usage_rollup_invalidation(affected_date); + END IF; + END IF; + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +-- INSERT 语句级触发器:每个批量 INSERT 只读一次状态行;当天写入既不后退水位也不记脏。 +CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state_after_insert() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + configured_timezone TEXT := current_setting('TimeZone'); + affected_date DATE; + state_closed_before DATE; + state_building_until DATE; + state_build_dirty_from DATE; + state_expired_before TIMESTAMPTZ; +BEGIN + IF NOT EXISTS (SELECT 1 FROM inserted_usage_logs WHERE group_id IS NOT NULL) THEN + RETURN NULL; + END IF; + + SELECT closed_before, building_until, build_dirty_from, expired_before + INTO state_closed_before, state_building_until, state_build_dirty_from, state_expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE; + + IF NOT FOUND THEN + RETURN NULL; + END IF; + + SELECT MIN((created_at AT TIME ZONE configured_timezone)::date) + INTO affected_date + FROM inserted_usage_logs + WHERE group_id IS NOT NULL + AND created_at >= state_expired_before; + + IF state_closed_before > affected_date + OR ( + state_building_until > affected_date + AND (state_build_dirty_from IS NULL OR state_build_dirty_from > affected_date) + ) THEN + PERFORM apply_group_usage_rollup_invalidation(affected_date); + END IF; + + RETURN NULL; +END; +$$; diff --git a/backend/migrations/group_usage_rollup_migration_test.go b/backend/migrations/group_usage_rollup_migration_test.go index f2e9a5d0ad..006a0b35c3 100644 --- a/backend/migrations/group_usage_rollup_migration_test.go +++ b/backend/migrations/group_usage_rollup_migration_test.go @@ -50,3 +50,22 @@ func TestMigration223TracksConfiguredTimezone(t *testing.T) { require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state") require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state_after_insert") } + +func TestMigration251AddsExpiredFloorAndNonBlockingBuildMarks(t *testing.T) { + content, err := FS.ReadFile("251_group_usage_rollup_nonblocking_build.sql") + require.NoError(t, err) + + sql := string(content) + require.Contains(t, sql, "SET LOCAL lock_timeout") + require.Contains(t, sql, "ADD COLUMN IF NOT EXISTS expired_before TIMESTAMPTZ NOT NULL") + require.Contains(t, sql, "ADD COLUMN IF NOT EXISTS building_until DATE") + require.Contains(t, sql, "ADD COLUMN IF NOT EXISTS build_dirty_from DATE") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION apply_group_usage_rollup_invalidation") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollups_at") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state()") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state_after_insert()") + require.Contains(t, sql, "created_at >= state_expired_before") + // 源记录变更只对状态行持 KEY SHARE,与 usage_logs 写入互不阻塞。 + require.Contains(t, sql, "FOR KEY SHARE") + require.NotContains(t, sql, "FOR UPDATE;") +} From fa910c1c3842a627a3b9372bf73e7cee11b26593 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 12:01:29 +0800 Subject: [PATCH 16/85] fix(usage): align five-hour window start with active quota resets --- backend/internal/repository/account_repo.go | 3 ++ .../usage_log_repo_integration_test.go | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 733ff9034b..c348af3c37 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -2714,8 +2714,11 @@ func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, s } func (r *accountRepository) UpdateSessionWindowEnd(ctx context.Context, id int64, end time.Time) error { + // Active five-hour quota reads must advance both bounds. Keeping the old + // start would charge the previous window against the new window's cost limit. _, err := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). + SetSessionWindowStart(end.Add(-5 * time.Hour)). SetSessionWindowEnd(end). Save(ctx) if err != nil { diff --git a/backend/internal/repository/usage_log_repo_integration_test.go b/backend/internal/repository/usage_log_repo_integration_test.go index 1ba7609fa4..15b9df2787 100644 --- a/backend/internal/repository/usage_log_repo_integration_test.go +++ b/backend/internal/repository/usage_log_repo_integration_test.go @@ -1308,6 +1308,34 @@ func (s *UsageLogRepoSuite) TestGetAccountWindowStats() { s.Require().Equal(int64(70), stats.Tokens) // (10+20) + (15+25) } +func (s *UsageLogRepoSuite) TestActiveFiveHourResetExcludesPreviousWindowCost() { + user := mustCreateUser(s.T(), s.client, &service.User{Email: "window-reset@test.com"}) + apiKey := mustCreateApiKey(s.T(), s.client, &service.APIKey{UserID: user.ID, Key: "sk-window-reset", Name: "k"}) + start := time.Now().UTC().Truncate(time.Second).Add(-30 * time.Minute) + oldStart := start.Add(-5 * time.Hour) + end := start.Add(5 * time.Hour) + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "window-reset", Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, + SessionWindowStart: &oldStart, SessionWindowEnd: &start, SessionWindowStatus: "allowed", + Extra: map[string]any{"window_cost_limit": 10.0, "window_cost_sticky_reserve": 1.0}, + }) + s.createUsageLog(user, apiKey, account, 10, 20, 20, start.Add(-time.Minute)) + s.createUsageLog(user, apiKey, account, 10, 20, 2, start.Add(time.Minute)) + accounts := newAccountRepositoryWithSQL(s.client, s.tx, nil) + + // Active quota reads persist this reset before another model response can + // supply session-window headers. Reload as the next scheduler/UI read does. + s.Require().NoError(accounts.UpdateSessionWindowEnd(s.ctx, account.ID, end)) + reloaded, err := accounts.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + stats, err := s.repo.GetAccountWindowStats(s.ctx, account.ID, reloaded.GetCurrentWindowStartTime()) + s.Require().NoError(err) + s.Require().Equal(int64(1), stats.Requests, "the previous window's request must not count in the new window") + s.Require().InDelta(2, stats.StandardCost, 0.000001) + s.Require().Equal(service.WindowCostSchedulable, reloaded.CheckWindowCostSchedulability(stats.StandardCost)) + s.Require().Equal("allowed", reloaded.SessionWindowStatus) +} + // --- GetUserUsageTrendByUserID --- func (s *UsageLogRepoSuite) TestGetUserUsageTrendByUserID() { From 6c79fdfc7ab55e2c067b475ee4a498efd12423c2 Mon Sep 17 00:00:00 2001 From: Anankke Date: Wed, 11 Nov 2026 18:32:26 -0800 Subject: [PATCH 17/85] fix(apicompat): send mid-conversation system messages to Responses as developer anthropicMsgToResponsesItems only distinguished assistant from everything else, so a role "system" message in the middle of messages (for example Claude Code hook output) was sent to Responses as a user item. Convert such messages to developer items, keeping content and order, as the Chat Completions to Responses conversion already does. --- .../pkg/apicompat/anthropic_to_responses.go | 10 ++++++ .../anthropic_translation_fidelity_test.go | 32 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go index b326241aa9..6cd8c2f18a 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go @@ -206,6 +206,16 @@ func anthropicMsgToResponsesItems(m AnthropicMessage) ([]ResponsesInputItem, err return anthropicUserToResponses(m.Content) case "assistant": return anthropicAssistantToResponses(m.Content) + case "system": + // Mid-conversation system turns (e.g. hook output) keep system-level + // authority: Responses uses developer for them, not user. + items, err := anthropicUserToResponses(m.Content) + for i := range items { + if items[i].Role == "user" { + items[i].Role = "developer" + } + } + return items, err default: return anthropicUserToResponses(m.Content) } diff --git a/backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go b/backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go new file mode 100644 index 0000000000..d0fe376287 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go @@ -0,0 +1,32 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// A system message in the middle of an Anthropic conversation (e.g. hook +// output) must reach Responses as a developer item, not as user input. +func TestAnthropicToResponses_MidConversationSystemBecomesDeveloper(t *testing.T) { + out, err := AnthropicToResponses(&AnthropicRequest{ + Model: "gpt-5.2", + MaxTokens: 64, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"hi"`)}, + {Role: "system", Content: json.RawMessage(`[{"type":"text","text":"hook output"}]`)}, + {Role: "system", Content: json.RawMessage(`"extra context"`)}, + }, + }) + require.NoError(t, err) + + input := gjson.ParseBytes(out.Input).Array() + require.Len(t, input, 3) + require.Equal(t, "user", input[0].Get("role").String()) + require.Equal(t, "developer", input[1].Get("role").String()) + require.Equal(t, "hook output", input[1].Get("content.0.text").String()) + require.Equal(t, "developer", input[2].Get("role").String()) + require.Equal(t, "extra context", input[2].Get("content.0.text").String()) +} From c829317fc5987b5d0608c861230b45325dd70d31 Mon Sep 17 00:00:00 2001 From: cyh Date: Thu, 12 Nov 2026 16:48:22 +0800 Subject: [PATCH 18/85] fix(anthropic): keep weekly usage readings across 5h rollovers A 5h window rollover cleared the sampled 7d and 7d_oi readings along with the 5h utilization. Only Fable responses carry 7d_oi, and a Fable-exhausted account stops receiving Fable requests, so its 7d F reading stayed empty until the weekly reset. Weekly thresholds also lost their input after every rollover. Clear the 5h utilization as before, but keep a weekly reading while its own reset is still ahead. Readings without a reset or past their reset are still cleared. --- .../ratelimit_rollover_weekly_usage_test.go | 123 ++++++++++++++++++ backend/internal/service/ratelimit_service.go | 42 ++++-- 2 files changed, 156 insertions(+), 9 deletions(-) create mode 100644 backend/internal/service/ratelimit_rollover_weekly_usage_test.go diff --git a/backend/internal/service/ratelimit_rollover_weekly_usage_test.go b/backend/internal/service/ratelimit_rollover_weekly_usage_test.go new file mode 100644 index 0000000000..86bb9fa802 --- /dev/null +++ b/backend/internal/service/ratelimit_rollover_weekly_usage_test.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "encoding/json" + "maps" + "net/http" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// applyExtraCalls applies UpdateExtra calls the way the JSONB merge does: +// a nil value is stored as JSON null. +func applyExtraCalls(extra map[string]any, calls []ueCall) map[string]any { + merged := maps.Clone(extra) + for _, call := range calls { + maps.Copy(merged, call.Updates) + } + return merged +} + +// A Fable-exhausted account stops receiving Fable requests, so its non-Fable +// responses carry 5h and 7d headers but no 7d_oi. A 5h rollover must keep the +// still-current 7d F reading instead of erasing it until the weekly reset. +func TestUpdateSessionWindow_RolloverKeepsCurrentWeeklyReadings(t *testing.T) { + now := time.Now() + weeklyReset := now.Add(72 * time.Hour).Unix() + expiredEnd := now.Add(-time.Minute) + extra := map[string]any{ + "session_window_utilization": 1.0, + "passive_usage_7d_utilization": 0.7, + "passive_usage_7d_reset": float64(weeklyReset), // as decoded from JSONB + "passive_usage_7d_oi_utilization": 1.0, + "passive_usage_7d_oi_reset": json.Number(strconv.FormatInt(weeklyReset, 10)), + "passive_usage_sampled_at": now.Add(-time.Hour).UTC().Format(time.RFC3339), + } + account := &Account{ID: 7, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, SessionWindowEnd: &expiredEnd, Extra: extra} + + headers := http.Header{} + headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") + headers.Set("anthropic-ratelimit-unified-5h-reset", strconv.FormatInt(now.Add(5*time.Hour).Unix(), 10)) + headers.Set("anthropic-ratelimit-unified-5h-utilization", "0.05") + headers.Set("anthropic-ratelimit-unified-7d-utilization", "0.71") + headers.Set("anthropic-ratelimit-unified-7d-reset", strconv.FormatInt(weeklyReset, 10)) + + repo := &sessionWindowMockRepo{} + newRateLimitServiceForTest(repo).UpdateSessionWindow(context.Background(), account, headers) + + require.Len(t, repo.updateExtraCalls, 2, "rollover clear, then the new sample") + require.Equal(t, map[string]any{"session_window_utilization": nil}, repo.updateExtraCalls[0].Updates) + + merged := applyExtraCalls(extra, repo.updateExtraCalls) + require.Equal(t, 0.05, merged["session_window_utilization"]) + require.Equal(t, 0.71, merged["passive_usage_7d_utilization"]) + require.Equal(t, 1.0, merged["passive_usage_7d_oi_utilization"], "7d F reading must survive a non-Fable rollover") + require.Equal(t, json.Number(strconv.FormatInt(weeklyReset, 10)), merged["passive_usage_7d_oi_reset"]) + require.NotNil(t, merged["passive_usage_sampled_at"]) + + fable := buildPassiveUsageWindow(merged, "passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset") + require.NotNil(t, fable) + require.Equal(t, 100.0, fable.Utilization) +} + +func TestRolloverPassiveUsageClears(t *testing.T) { + now := time.Now() + future := now.Add(24 * time.Hour).Unix() + past := now.Add(-time.Hour).Unix() + weekly := []string{"passive_usage_7d_utilization", "passive_usage_7d_reset"} + fable := []string{"passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset"} + + for _, tc := range []struct { + name string + extra map[string]any + cleared []string + kept []string + clearSample bool + }{ + { + name: "both current", + extra: map[string]any{"passive_usage_7d_reset": future, "passive_usage_7d_oi_reset": float64(future)}, + kept: append(weekly, fable...), + }, + { + name: "weekly expired, fable current", + extra: map[string]any{"passive_usage_7d_reset": past, "passive_usage_7d_oi_reset": strconv.FormatInt(future, 10)}, + cleared: weekly, + kept: fable, + }, + { + name: "reading without reset is stale", + extra: map[string]any{"passive_usage_7d_utilization": 0.4, "passive_usage_7d_oi_reset": nil}, + cleared: append(weekly, fable...), + clearSample: true, + }, + { + name: "no extra", + cleared: append(weekly, fable...), + clearSample: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + updates := rolloverPassiveUsageClears(tc.extra, now) + require.Contains(t, updates, "session_window_utilization") + require.Nil(t, updates["session_window_utilization"]) + for _, key := range tc.cleared { + value, present := updates[key] + require.True(t, present, key) + require.Nil(t, value, key) + } + for _, key := range tc.kept { + require.NotContains(t, updates, key) + } + if tc.clearSample { + require.Contains(t, updates, "passive_usage_sampled_at") + } else { + require.NotContains(t, updates, "passive_usage_sampled_at") + } + }) + } +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 61c065ec0d..c620685ad2 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2104,16 +2104,10 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc slog.Info("account_session_window_initialized", "account_id", account.ID, "window_start", start, "window_end", end, "status", status) } - // 窗口重置时清除旧的 utilization 和被动采样数据,避免残留上个窗口的数据 + // 5h 窗口重置时清除上个 5h 窗口的 utilization。周窗口有自己的重置时间, + // 只清除已经过期的周读数(见 rolloverPassiveUsageClears)。 if windowEnd != nil && needInitWindow { - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ - "session_window_utilization": nil, - "passive_usage_7d_utilization": nil, - "passive_usage_7d_reset": nil, - "passive_usage_7d_oi_utilization": nil, - "passive_usage_7d_oi_reset": nil, - "passive_usage_sampled_at": nil, - }) + _ = s.accountRepo.UpdateExtra(ctx, account.ID, rolloverPassiveUsageClears(account.Extra, time.Now())) } if err := s.accountRepo.UpdateSessionWindow(ctx, account.ID, windowStart, windowEnd, status); err != nil { @@ -2131,6 +2125,36 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc } } +// passiveWeeklyUsageWindows lists the sampled weekly windows as utilization/reset Extra keys. +var passiveWeeklyUsageWindows = [...][2]string{ + {"passive_usage_7d_utilization", "passive_usage_7d_reset"}, + {"passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset"}, +} + +// rolloverPassiveUsageClears returns the Extra updates for a 5h window rollover. +// The 5h utilization always belongs to the previous window. A weekly reading +// is kept while its own reset is still ahead: only Fable responses carry 7d_oi, +// so a Fable-exhausted account that no longer receives Fable traffic would +// otherwise lose its 7d F reading at every rollover until the weekly reset. +// Readings with no reset, or a reset that has passed, are stale and cleared. +func rolloverPassiveUsageClears(extra map[string]any, now time.Time) map[string]any { + updates := map[string]any{"session_window_utilization": nil} + kept := false + for _, keys := range passiveWeeklyUsageWindows { + if reset := parseExtraFloat64(extra[keys[1]]); reset > 0 && time.Unix(int64(reset), 0).After(now) { + kept = true + continue + } + updates[keys[0]] = nil + updates[keys[1]] = nil + } + // The sample time still describes any weekly reading that was kept. + if !kept { + updates["passive_usage_sampled_at"] = nil + } + return updates +} + // samplePassiveUsageFromHeaders 从 Anthropic 响应头收集 5h/7d/7d_oi 的 // utilization 与 reset 被动采样数据,合并为一次 Extra 写入。无数据时不写。 func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, account *Account, headers http.Header) { From 733722f8c7de5f459a490957c36344cb8e20b019 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 02:51:28 -0800 Subject: [PATCH 19/85] fix(gateway): retain sticky writes after client disconnects --- backend/internal/handler/gateway_handler.go | 8 +- .../handler/gateway_sticky_writeback_test.go | 186 ++++++++++++++++++ 2 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 backend/internal/handler/gateway_sticky_writeback_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 6ec51d5430..60fbd38f59 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1127,8 +1127,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定, // 下次请求粘性账号恢复后仍可命中 if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) { - if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil { - reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + // Forward has completed; finish the bounded write even if the client disconnects. + bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second) + bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID) + cancelBind() + if bindErr != nil { + reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(bindErr)) } } diff --git a/backend/internal/handler/gateway_sticky_writeback_test.go b/backend/internal/handler/gateway_sticky_writeback_test.go new file mode 100644 index 0000000000..2045f2792f --- /dev/null +++ b/backend/internal/handler/gateway_sticky_writeback_test.go @@ -0,0 +1,186 @@ +//go:build unit + +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type stickyWritebackContextKey struct{} + +type stickyWritebackCall struct { + err error + groupID int64 + account int64 + session string + ttl time.Duration + value any + deadline time.Time +} + +type stickyWritebackCache struct { + service.GatewayCache + accountID int64 + finished bool + calls []stickyWritebackCall +} + +func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) { + return s.accountID, nil +} + +func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error { + if s.finished { + deadline, _ := ctx.Deadline() + s.calls = append(s.calls, stickyWritebackCall{ + err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl, + value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline, + }) + } + if err := ctx.Err(); err != nil { + return err + } + s.accountID = account + return nil +} + +func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { + return nil +} + +func (s *stickyWritebackCache) DeleteSessionAccountID(context.Context, int64, string) error { + s.accountID = 0 + return nil +} + +type stickyWritebackBody struct { + io.Reader + finish func() +} + +func (b *stickyWritebackBody) Close() error { + b.finish() + return nil +} + +func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + name := "buffered" + if stream { + name = "streaming" + } + for _, tt := range []struct { + name string + bound int64 + cancel bool + fail bool + wantWrites int + }{ + {name: "new binding", wantWrites: 1}, + {name: "new binding after disconnect", cancel: true, wantWrites: 1}, + {name: "refresh binding", bound: 9401, wantWrites: 1}, + {name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1}, + {name: "different binding", bound: 9499, cancel: true}, + {name: "forward failed", cancel: true, fail: true}, + } { + t.Run(name+"/"+tt.name, func(t *testing.T) { + groupID := int64(9400) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + Extra: map[string]any{"anthropic_passthrough": true}, + AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}}, + } + cache := &stickyWritebackCache{accountID: tt.bound} + ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value") + ctx, cancel := context.WithTimeout(ctx, 4*time.Second) + t.Cleanup(cancel) + responseBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}` + contentType := "application/json" + if stream { + responseBody = compatStreamUsagePartialStream + compatStreamUsageCompletion + contentType = "text/event-stream" + } + status := http.StatusOK + if tt.fail { + status = http.StatusBadRequest + responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}` + } + upstream := &compatStreamUsageUpstream{response: &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() { + // Forward closes its upstream body on return. Cancel precisely + // after that work, before the handler's terminal sticky write. + cache.finished = true + if tt.cancel { + cancel() + } + }}, + }} + cfg := &config.Config{RunMode: config.RunModeSimple} + other := *account + other.ID = 9499 + other.Schedulable = false + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil) + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + requestBody := `{"model":"claude-sonnet-4.5","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"sticky writeback test"}]}` + if stream { + requestBody = strings.Replace(requestBody, `"stream":false`, `"stream":true`, 1) + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + key := &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100}} + c.Set(string(middleware.ContextKeyAPIKey), key) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403}) + + h.Messages(c) + + require.Equal(t, 1, upstream.calls) + require.True(t, cache.finished) + require.Equal(t, status, rec.Code) + if tt.cancel { + require.ErrorIs(t, ctx.Err(), context.Canceled) + } + require.Len(t, cache.calls, tt.wantWrites) + for _, call := range cache.calls { + require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write") + require.Equal(t, groupID, call.groupID) + require.Equal(t, account.ID, call.account) + require.NotEmpty(t, call.session) + require.Positive(t, call.ttl) + require.Equal(t, "request-scoped value", call.value) + require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline") + require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second) + } + }) + } + } +} From d30179f4b5c8f56750fea3d6a7a3f74d50796230 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 03:12:37 -0800 Subject: [PATCH 20/85] fix(usage): retain native Anthropic response observations --- ...penai_gateway_messages_anthropic_native.go | 50 +++-- ...teway_native_anthropic_observation_test.go | 195 ++++++++++++++++++ 2 files changed, 223 insertions(+), 22 deletions(-) create mode 100644 backend/internal/service/openai_gateway_native_anthropic_observation_test.go diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 3156aa8546..3c9a92c554 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -276,16 +276,19 @@ func (s *OpenAIGatewayService) handleNativeAnthropicBufferedResponse( c.Data(resp.StatusCode, contentType, body) return &OpenAIForwardResult{ - RequestID: resp.Header.Get("x-request-id"), - UpstreamHeaders: resp.Header, - Usage: claudeUsageToOpenAIUsage(usage), - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - UpstreamEndpoint: "/v1/messages", - Stream: false, - ReasoningEffort: reasoningEffort, - Duration: time.Since(startTime), + RequestID: resp.Header.Get("x-request-id"), + UpstreamHeaders: resp.Header, + Usage: claudeUsageToOpenAIUsage(usage), + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + UpstreamEndpoint: "/v1/messages", + Stream: false, + ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), }, nil } @@ -559,18 +562,21 @@ func (s *OpenAIGatewayService) nativeAnthropicStreamResult( usage = &ClaudeUsage{} } return &OpenAIForwardResult{ - RequestID: resp.Header.Get("x-request-id"), - UpstreamHeaders: resp.Header, - Usage: claudeUsageToOpenAIUsage(usage), - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - UpstreamEndpoint: "/v1/messages", - Stream: true, - ReasoningEffort: reasoningEffort, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - ClientDisconnect: clientDisconnect, + RequestID: resp.Header.Get("x-request-id"), + UpstreamHeaders: resp.Header, + Usage: claudeUsageToOpenAIUsage(usage), + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + UpstreamEndpoint: "/v1/messages", + Stream: true, + ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: clientDisconnect, } } diff --git a/backend/internal/service/openai_gateway_native_anthropic_observation_test.go b/backend/internal/service/openai_gateway_native_anthropic_observation_test.go new file mode 100644 index 0000000000..3decfa9f64 --- /dev/null +++ b/backend/internal/service/openai_gateway_native_anthropic_observation_test.go @@ -0,0 +1,195 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func nativeObservationResponse(t *testing.T, stream bool, model, speed string, conflict, partial, readError bool) (*http.Response, string) { + t.Helper() + usage := map[string]any{"input_tokens": 20, "output_tokens": 10} + if speed != "" { + usage["speed"] = speed + } + message := map[string]any{ + "id": "msg_observed", "type": "message", "role": "assistant", + "content": []map[string]string{{"type": "text", "text": "observed response"}}, "usage": usage, + } + if model != "" { + message["model"] = model + } + encode := func(v any) string { + b, err := json.Marshal(v) + require.NoError(t, err) + return string(b) + } + wire := encode(message) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + usage["output_tokens"] = 1 + message["content"] = []any{} + wire = "event: message_start\ndata: " + encode(map[string]any{"type": "message_start", "message": message}) + "\n\n" + if conflict { + message["model"] = "conflicting-model" + usage["speed"] = "standard" + wire += "event: message_start\ndata: " + encode(map[string]any{"type": "message_start", "message": message}) + "\n\n" + } + wire += "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"observed response\"}}\n\n" + if !partial { + wire += "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n" + + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":10}}\n\n" + + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + } + var body io.ReadCloser = io.NopCloser(strings.NewReader(wire)) + if readError { + body = &streamReadCloser{payload: []byte(wire), err: io.ErrUnexpectedEOF} + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "Content-Type": []string{contentType}, "X-Request-Id": []string{"native-observed"}, + }, Body: body}, wire +} + +func TestNativeAnthropicResponseObservationReachesUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tt := range []struct { + name string + stream bool + model string + speed string + conflict bool + partial bool + readError bool + disconnect bool + wantModel string + wantSpeed string + }{ + {name: "buffered matching", model: " k3 ", speed: "standard", wantModel: "k3", wantSpeed: "standard"}, + {name: "buffered mismatch", model: "reported-k3", speed: "fast", wantModel: "reported-k3", wantSpeed: "fast"}, + {name: "buffered undeclared", speed: "fast"}, + {name: "stream matching", stream: true, model: "k3", speed: "standard", wantModel: "k3", wantSpeed: "standard"}, + {name: "stream mismatch", stream: true, model: "reported-k3", speed: "fast", wantModel: "reported-k3", wantSpeed: "fast"}, + {name: "stream undeclared", stream: true, speed: "fast"}, + {name: "stream conflicting declarations", stream: true, model: "reported-k3", speed: "fast", conflict: true, wantModel: "reported-k3"}, + {name: "stream truncated", stream: true, model: "reported-k3", speed: "standard", partial: true, wantModel: "reported-k3", wantSpeed: "standard"}, + {name: "stream read error", stream: true, model: "reported-k3", speed: "standard", partial: true, readError: true, wantModel: "reported-k3", wantSpeed: "standard"}, + {name: "client disconnected", stream: true, model: "reported-k3", speed: "fast", disconnect: true, wantModel: "reported-k3", wantSpeed: "fast"}, + } { + t.Run(tt.name, func(t *testing.T) { + resp, wire := nativeObservationResponse(t, tt.stream, tt.model, tt.speed, tt.conflict, tt.partial, tt.readError) + upstream := &httpUpstreamRecorder{resp: resp} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body, err := json.Marshal(map[string]any{ + "model": "client-model", "max_tokens": 32, "stream": tt.stream, + "messages": []map[string]string{{"role": "user", "content": "hi"}}, + }) + require.NoError(t, err) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))) + if tt.disconnect { + c.Writer = &failWriteResponseWriter{ResponseWriter: c.Writer} + } + // A previous attempt must not leak its declaration into an undeclared response. + beginUpstreamResponseModelObservation(c).Observe("stale-model", false) + account := nativeAnthropicTestAccount() + result, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "k3") + if tt.partial { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, "k3", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "client-model", result.Model) + require.Equal(t, "k3", result.BillingModel) + require.Equal(t, "k3", result.UpstreamModel) + require.Equal(t, 20, result.Usage.InputTokens) + wantOutput := 10 + if tt.partial { + wantOutput = 0 + } + require.Equal(t, wantOutput, result.Usage.OutputTokens) + require.Equal(t, tt.disconnect, result.ClientDisconnect) + if !tt.disconnect { + require.Equal(t, wire, rec.Body.String(), "observation must preserve the upstream response bytes") + } + require.Equal(t, tt.wantModel, observedUpstreamResponseModel(c), "the observer already saw the declaration") + + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + usageSvc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.NoError(t, usageSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, APIKey: &APIKey{ID: 10}, User: &User{ID: 20}, Account: account, + })) + require.NotNil(t, usageRepo.lastLog) + log := usageRepo.lastLog + require.Equal(t, "k3", *log.UpstreamModel) + if tt.wantModel == "" { + require.Nil(t, log.UpstreamResponseModel) + require.Nil(t, log.UpstreamModelMismatch) + } else { + require.NotNil(t, log.UpstreamResponseModel) + require.Equal(t, tt.wantModel, *log.UpstreamResponseModel) + require.NotNil(t, log.UpstreamModelMismatch) + require.Equal(t, tt.wantModel != "k3", *log.UpstreamModelMismatch) + } + require.Equal(t, tt.wantModel, result.UpstreamResponseModel) + require.Equal(t, tt.conflict, result.UpstreamResponseModelConflict) + require.Equal(t, tt.wantSpeed, result.UpstreamResponseServiceTier) + }) + } +} + +func TestNativeAnthropicResponseObservationRespectsBillingSource(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + for _, source := range []string{BillingModelSourceChannelMapped, BillingModelSourceResponse} { + name := "buffered/" + source + if stream { + name = "stream/" + source + } + t.Run(name, func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + usageSvc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil) + cheaper, pricier, cheapCost, baselineCost := orderedResponseBillingModels(t, usageSvc.billingService, + UsageTokens{InputTokens: 20, OutputTokens: 10}, openAICheapFixtureModel, openAIPriceyFixtureModel) + resp, _ := nativeObservationResponse(t, stream, cheaper, "standard", false, false, false) + upstream := &httpUpstreamRecorder{resp: resp} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body, err := json.Marshal(map[string]any{ + "model": pricier, "max_tokens": 32, "stream": stream, + "messages": []map[string]string{{"role": "user", "content": "hi"}}, + }) + require.NoError(t, err) + account := nativeAnthropicTestAccount() + result, err := svc.ForwardAsAnthropic(context.Background(), adaptiveProtocolTestContext("/v1/messages", body), account, body, "", "") + require.NoError(t, err) + require.NoError(t, usageSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, APIKey: &APIKey{ID: 10}, User: &User{ID: 20}, Account: account, + ChannelUsageFields: ChannelUsageFields{ChannelID: 9, OriginalModel: pricier, ChannelMappedModel: pricier, BillingModelSource: source}, + })) + wantCost := baselineCost + if source == BillingModelSourceResponse { + wantCost = cheapCost + } + require.NotNil(t, usageRepo.lastLog) + require.InDelta(t, wantCost.ActualCost, usageRepo.lastLog.ActualCost, 1e-12) + require.InDelta(t, wantCost.ActualCost, userRepo.lastAmount, 1e-12) + }) + } + } +} From ac981240cc44f4e61bf76aa1b67eb1a5436aab30 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 03:25:41 -0800 Subject: [PATCH 21/85] fix(usage): retain response models through Chat fallbacks --- ..._gateway_chat_fallback_observation_test.go | 162 ++++++++++++++++++ .../openai_gateway_messages_chat_fallback.go | 80 +++++---- .../openai_gateway_responses_chat_fallback.go | 102 ++++++----- 3 files changed, 260 insertions(+), 84 deletions(-) create mode 100644 backend/internal/service/openai_gateway_chat_fallback_observation_test.go diff --git a/backend/internal/service/openai_gateway_chat_fallback_observation_test.go b/backend/internal/service/openai_gateway_chat_fallback_observation_test.go new file mode 100644 index 0000000000..6aa69b3a56 --- /dev/null +++ b/backend/internal/service/openai_gateway_chat_fallback_observation_test.go @@ -0,0 +1,162 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func chatObservationResponse(t *testing.T, stream bool, model string, conflict, readError, invalidTool bool) *http.Response { + t.Helper() + encode := func(v any) string { + b, err := json.Marshal(v) + require.NoError(t, err) + return string(b) + } + usage := map[string]int{"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30} + payload := map[string]any{"id": "chatcmpl_observed", "service_tier": "default", "usage": usage} + if model != "" { + payload["model"] = model + } + payload["choices"] = []any{map[string]any{ + "index": 0, "message": map[string]string{"role": "assistant", "content": "observed response"}, "finish_reason": "stop", + }} + wire := encode(payload) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + payload["choices"] = []any{map[string]any{ + "index": 0, "delta": map[string]string{"role": "assistant", "content": "observed response"}, "finish_reason": nil, + }} + if invalidTool { + payload["choices"] = []any{map[string]any{"index": 0, "delta": map[string]any{ + "tool_calls": []any{map[string]any{"index": 0, "id": "call_bad", "type": "function", + "function": map[string]string{"name": "lookup", "arguments": "{"}}}, + }, "finish_reason": nil}} + } + wire = "data: " + encode(payload) + "\n\n" + if conflict { + payload["model"] = "conflicting-model" + wire += "data: " + encode(payload) + "\n\n" + } + if !readError { + wire += "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":10,\"total_tokens\":30}}\n\n" + + "data: [DONE]\n\n" + } + } + var body io.ReadCloser = io.NopCloser(strings.NewReader(wire)) + if readError { + body = &errTailReader{data: []byte(wire), err: io.ErrUnexpectedEOF} + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "Content-Type": []string{contentType}, "X-Request-Id": []string{"chat-observed"}, + }, Body: body} +} + +func TestChatFallbackResponseObservationReachesUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"messages", "responses"} { + for _, tt := range []struct { + name string + stream bool + model string + conflict bool + readError bool + disconnect bool + invalidTool bool + }{ + {name: "buffered matching", model: "gpt-5.4"}, + {name: "buffered mismatch", model: "reported-model"}, + {name: "buffered undeclared"}, + {name: "stream matching", stream: true, model: "gpt-5.4"}, + {name: "stream mismatch", stream: true, model: "reported-model"}, + {name: "stream undeclared", stream: true}, + {name: "stream conflicting", stream: true, model: "reported-model", conflict: true}, + {name: "stream read error", stream: true, model: "reported-model", readError: true}, + {name: "client disconnected", stream: true, model: "reported-model", disconnect: true}, + {name: "invalid tool arguments", stream: true, model: "reported-model", invalidTool: true}, + } { + if tt.invalidTool && endpoint != "responses" { + continue + } + t.Run(endpoint+"/"+tt.name, func(t *testing.T) { + request := map[string]any{"model": "gpt-5.4", "stream": tt.stream} + if endpoint == "messages" { + request["max_tokens"] = 32 + request["messages"] = []map[string]string{{"role": "user", "content": "hi"}} + } else { + request["input"] = "hi" + } + body, err := json.Marshal(request) + require.NoError(t, err) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + if tt.disconnect { + c.Writer = &failWriteResponseWriter{ResponseWriter: c.Writer} + } + upstream := &httpUpstreamRecorder{resp: chatObservationResponse(t, tt.stream, tt.model, tt.conflict, tt.readError, tt.invalidTool)} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := forceChatMessagesFallbackAccount() + var result *OpenAIForwardResult + if endpoint == "messages" { + result, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } else { + account = forceChatResponsesFallbackAccount() + result, err = svc.Forward(context.Background(), c, account, body) + } + if tt.readError || tt.invalidTool { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, "/v1/chat/completions", upstream.lastReq.URL.Path) + require.Equal(t, "gpt-5.4", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "gpt-5.4", result.Model) + require.Equal(t, "gpt-5.4", result.UpstreamModel) + require.Equal(t, 20, result.Usage.InputTokens) + require.Equal(t, 10, result.Usage.OutputTokens) + if !tt.disconnect && !tt.invalidTool { + require.Contains(t, rec.Body.String(), "observed response") + } + require.Equal(t, tt.model, observedUpstreamResponseModel(c), "the shared pipeline already saw the upstream model") + wantTier := "default" + if tt.model == "" { + wantTier = "" + } + require.Equal(t, wantTier, result.UpstreamResponseServiceTier) + + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + usageSvc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.NoError(t, usageSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, APIKey: &APIKey{ID: 10}, User: &User{ID: 20}, Account: account, + })) + require.NotNil(t, usageRepo.lastLog) + log := usageRepo.lastLog + if tt.model == "" { + require.Nil(t, log.UpstreamResponseModel) + require.Nil(t, log.UpstreamModelMismatch) + } else { + require.NotNil(t, log.UpstreamResponseModel) + require.Equal(t, tt.model, *log.UpstreamResponseModel) + require.NotNil(t, log.UpstreamModelMismatch) + require.Equal(t, tt.model != "gpt-5.4", *log.UpstreamModelMismatch) + } + require.Equal(t, tt.model, result.UpstreamResponseModel) + require.Equal(t, tt.conflict, result.UpstreamResponseModelConflict) + }) + } + } +} diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index 0a92e5963a..2b96f35be8 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -178,17 +178,19 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( c.JSON(http.StatusOK, anthropicResp) return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: false, - Duration: time.Since(startTime), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -240,19 +242,21 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( // masks the truncation, and surface the error to flag usage incomplete // (mirrors forwardResponsesViaRawChatCompletions). return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, - ClientDisconnect: clientDisconnected, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, + ClientDisconnect: clientDisconnected, }, fmt.Errorf("stream usage incomplete: %w", scan.Err) } @@ -277,18 +281,20 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( } return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, - ClientDisconnect: clientDisconnected, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, + ClientDisconnect: clientDisconnected, }, nil } diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index 154a0b18e1..3b82eae8f5 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -169,17 +169,19 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( c.JSON(http.StatusOK, responsesResp) return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: false, - Duration: time.Since(startTime), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -241,34 +243,38 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( if scan.Err != nil { return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: scan.Usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: scan.Usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, }, fmt.Errorf("stream usage incomplete: %w", scan.Err) } if err := state.ValidateToolCallArguments(); err != nil { return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: scan.Usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: scan.Usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, }, fmt.Errorf("invalid tool call arguments from upstream: %w", err) } @@ -289,18 +295,20 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( } return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: scan.Usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: scan.Usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, }, nil } From 636981b28b22fb217222035617c77e7cf7adbe60 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 03:46:32 -0800 Subject: [PATCH 22/85] test(scheduler): reproduce cooldown expiry absent from snapshots --- ...cheduler_snapshot_transient_expiry_test.go | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 backend/internal/service/scheduler_snapshot_transient_expiry_test.go diff --git a/backend/internal/service/scheduler_snapshot_transient_expiry_test.go b/backend/internal/service/scheduler_snapshot_transient_expiry_test.go new file mode 100644 index 0000000000..83cf7516de --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_transient_expiry_test.go @@ -0,0 +1,109 @@ +package service + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type transientExpirySnapshotCache struct { + SchedulerCache + accounts []*Account + hit bool +} + +func (c *transientExpirySnapshotCache) GetSnapshot(context.Context, SchedulerBucket) ([]*Account, bool, error) { + return c.accounts, c.hit, nil +} + +func (c *transientExpirySnapshotCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *transientExpirySnapshotCache) SetSnapshot(_ context.Context, _ SchedulerBucket, _ SchedulerBucketWriteToken, accounts []Account) error { + c.accounts = nil + for _, account := range accounts { + copy := account + c.accounts = append(c.accounts, ©) + } + c.hit = true + return nil +} + +type transientExpiryAccountRepo struct { + AccountRepository + accounts []Account + calls int +} + +// Match the current repository contract: the source query excludes accounts +// while any transient cooldown is in the future. +func (r *transientExpiryAccountRepo) ListSchedulableByPlatform(context.Context, string) ([]Account, error) { + r.calls++ + var accounts []Account + for _, account := range r.accounts { + if account.IsSchedulable() { + accounts = append(accounts, account) + } + } + return accounts, nil +} + +func TestSchedulerSnapshotRecoversTransientCooldownWithoutIntervalRebuild(t *testing.T) { + for _, field := range []string{"rate_limit_reset_at", "overload_until", "temp_unschedulable_until"} { + t.Run(field, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + until := time.Now().Add(30 * time.Second) + ready := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + cooling := ready + cooling.ID = 2 + switch field { + case "rate_limit_reset_at": + cooling.RateLimitResetAt = &until + case "overload_until": + cooling.OverloadUntil = &until + case "temp_unschedulable_until": + cooling.TempUnschedulableUntil = &until + } + repo := &transientExpiryAccountRepo{accounts: []Account{ready, cooling}} + cache := &transientExpirySnapshotCache{} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.Scheduling.DbFallbackEnabled = true + svc := NewSchedulerSnapshotService(cache, nil, repo, nil, cfg) + eligible := func(accounts []Account) []int64 { + var ids []int64 + for _, account := range accounts { + if account.IsSchedulable() { + ids = append(ids, account.ID) + } + } + return ids + } + + accounts, _, err := svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) + require.NoError(t, err) + require.Equal(t, []int64{1}, eligible(accounts)) + require.True(t, cache.hit) + require.Equal(t, 1, repo.calls) + + time.Sleep(31 * time.Second) + require.True(t, cooling.IsSchedulable(), "the account's own cooldown has expired") + accounts, _, err = svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) + require.NoError(t, err) + t.Logf("after expiry: eligible=%v cached_members=%d source_calls=%d", eligible(accounts), len(cache.accounts), repo.calls) + assert.ElementsMatch(t, []int64{1, 2}, eligible(accounts), "an expired cooldown must not wait for the interval rebuild") + + // Positive control: a fresh source read immediately restores the account. + cache.hit = false + accounts, _, err = svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) + require.NoError(t, err) + require.ElementsMatch(t, []int64{1, 2}, eligible(accounts)) + }) + }) + } +} From 39bac35a374f53264a353b69ed21661de9849971 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 05:12:33 -0800 Subject: [PATCH 23/85] fix(scheduler): retain cooling accounts in snapshot membership --- ...er_snapshot_membership_integration_test.go | 125 ++++++++++++++++++ backend/internal/service/account_service.go | 4 +- .../billing_inflight_reservation_test.go | 8 +- .../service/gateway_multiplatform_test.go | 5 +- .../scheduler_snapshot_batch_query_test.go | 10 +- .../scheduler_snapshot_cancellation_test.go | 2 +- ...er_snapshot_full_rebuild_lifecycle_test.go | 8 +- ...scheduler_snapshot_group_lifecycle_test.go | 6 +- .../scheduler_snapshot_outbox_cleanup_test.go | 2 +- .../scheduler_snapshot_retirement_test.go | 3 +- .../service/scheduler_snapshot_service.go | 62 ++++----- ...cheduler_snapshot_transient_expiry_test.go | 28 +++- 12 files changed, 206 insertions(+), 57 deletions(-) create mode 100644 backend/internal/repository/scheduler_snapshot_membership_integration_test.go diff --git a/backend/internal/repository/scheduler_snapshot_membership_integration_test.go b/backend/internal/repository/scheduler_snapshot_membership_integration_test.go new file mode 100644 index 0000000000..457fcce5a7 --- /dev/null +++ b/backend/internal/repository/scheduler_snapshot_membership_integration_test.go @@ -0,0 +1,125 @@ +//go:build integration + +package repository + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSchedulerSnapshotConfiguredMembership(t *testing.T) { + for _, platform := range []string{service.PlatformOpenAI, service.PlatformAnthropic, service.PlatformGemini} { + t.Run(platform, func(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + client := tx.Client() + repo := newAccountRepositoryWithSQL(client, tx, nil) + group := mustCreateGroup(t, client, &service.Group{Name: "snapshot-pool", Platform: platform}) + other := mustCreateGroup(t, client, &service.Group{Name: "snapshot-other", Platform: platform}) + future, past := time.Now().Add(time.Hour), time.Now().Add(-time.Hour) + ids := make(map[int64]map[string]int64) + for _, gid := range []int64{0, group.ID, other.ID} { + ids[gid] = make(map[string]int64) + for _, kind := range []string{"ready", "cooling", "expired", "manual", "disabled", "deleted", "other_platform", "mixed_on", "mixed_off"} { + accountPlatform := platform + if kind == "mixed_on" || kind == "mixed_off" { + accountPlatform = service.PlatformAntigravity + } + if kind == "other_platform" { + accountPlatform = service.PlatformGrok + if platform == accountPlatform { + accountPlatform = service.PlatformOpenAI + } + } + create := client.Account.Create().SetName(fmt.Sprintf("%s-%d", kind, gid)). + SetPlatform(accountPlatform).SetType(service.AccountTypeAPIKey). + SetCredentials(map[string]any{}).SetExtra(map[string]any{"mixed_scheduling": kind == "mixed_on"}). + SetStatus(service.StatusActive).SetSchedulable(kind != "manual") + switch kind { + case "cooling": + create.SetRateLimitResetAt(future).SetOverloadUntil(future).SetTempUnschedulableUntil(future) + case "expired": + create.SetExpiresAt(past).SetAutoPauseOnExpired(true) + case "disabled": + create.SetStatus(service.StatusDisabled) + case "deleted": + create.SetDeletedAt(past) + } + account, err := create.Save(ctx) + require.NoError(t, err) + ids[gid][kind] = account.ID + if gid > 0 { + _, err = client.AccountGroup.Create().SetAccountID(account.ID).SetGroupID(gid).Save(ctx) + require.NoError(t, err) + } + } + } + + for _, scope := range []string{"simple", "group", "ungrouped"} { + for _, forced := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/forced=%t", scope, forced), func(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Gateway.Scheduling.DbFallbackEnabled = true + var groupID *int64 + groups := []int64{0} + if scope == "group" { + groupID, groups = &group.ID, []int64{group.ID} + } + if scope == "simple" { + cfg.RunMode = config.RunModeSimple + groupID, groups = &group.ID, []int64{0, group.ID, other.ID} + } + mixed := platform != service.PlatformOpenAI && !forced + var wantReady, wantMembers []int64 + for _, gid := range groups { + wantReady = append(wantReady, ids[gid]["ready"]) + wantMembers = append(wantMembers, ids[gid]["ready"], ids[gid]["cooling"], ids[gid]["expired"]) + if mixed { + wantReady = append(wantReady, ids[gid]["mixed_on"]) + wantMembers = append(wantMembers, ids[gid]["mixed_on"]) + } + } + cache := NewSchedulerCache(testRedis(t)) + svc := service.NewSchedulerSnapshotService(cache, nil, repo, nil, cfg) + accountIDs := func(accounts []service.Account) []int64 { + out := make([]int64, len(accounts)) + for i := range accounts { + out[i] = accounts[i].ID + } + return out + } + for range 2 { + accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, groupID, platform, forced) + require.NoError(t, err) + require.Equal(t, mixed, useMixed) + require.ElementsMatch(t, wantReady, accountIDs(accounts), "both DB fallback and cache hit enforce current eligibility") + } + bucket := service.SchedulerBucket{Platform: platform, Mode: service.SchedulerModeSingle} + if scope == "group" { + bucket.GroupID = group.ID + } + if forced { + bucket.Mode = service.SchedulerModeForced + } else if mixed { + bucket.Mode = service.SchedulerModeMixed + } + members, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + memberIDs := make([]int64, len(members)) + for i := range members { + memberIDs[i] = members[i].ID + } + require.ElementsMatch(t, wantMembers, memberIDs, "the stored pool retains timed blocks without widening platform/group or manual eligibility") + }) + } + } + }) + } +} diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 7980a5c447..e2fa3ed08c 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -94,8 +94,8 @@ type AccountRepository interface { ListSchedulableUngroupedByPlatforms(ctx context.Context, platforms []string) ([]Account, error) // ListModelAvailabilityCandidates returns accounts that are enabled by // persistent configuration (active + schedulable) for model-support - // diagnosis. It deliberately does not filter transient runtime state such - // as rate-limit, overload, temporary-unschedulable, or expiry windows. + // diagnosis and scheduler snapshot membership. It deliberately does not + // filter rate-limit, overload, temporary-unschedulable, or expiry windows. // When groupID is nil, includeGrouped controls whether the query scans all // matching accounts or only accounts without a group binding. ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error) diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index fa9281823b..5018652610 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -359,8 +359,8 @@ func TestInflightEstimate_AccountLevelMappingFallsBackLikeBilling(t *testing.T) groupID := int64(31) svc := newInflightEstimateGateway(t, nil) snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(groupID, PlatformAnthropic): { - {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}}, - {ID: 2, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-opus-4-1"}}}, + {ID: 1, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}}, + {ID: 2, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-opus-4-1"}}}, }}} attachInflightSnapshot(svc, snap) apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} @@ -468,7 +468,7 @@ func TestInflightEstimate_AccountMappingNoDBAndBoundedMemory(t *testing.T) { func TestInflightEstimate_NoGroupKeyUsesUngroupedAccountMapping(t *testing.T) { svc := newInflightEstimateGateway(t, nil) snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(0, PlatformAnthropic): { - {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-nog": "claude-opus-4-1"}}}, + {ID: 1, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-nog": "claude-opus-4-1"}}}, }}} attachInflightSnapshot(svc, snap) apiKey := &APIKey{User: &User{ID: 1}} @@ -493,7 +493,7 @@ func TestInflightEstimate_AccountMappingNoNegativeCaching(t *testing.T) { _, priced := svc.EstimateInflightReservation(ctx, apiKey, req) require.False(t, priced) - snap.set(groupID, PlatformAnthropic, []Account{{ID: 9, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-*": "claude-sonnet-4-5"}}}}) + snap.set(groupID, PlatformAnthropic, []Account{{ID: 9, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-*": "claude-sonnet-4-5"}}}}) est, priced := svc.EstimateInflightReservation(ctx, apiKey, req) require.True(t, priced, "new mapping (incl. wildcard) visible on next request") require.Greater(t, est, 0.0) diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index badb2427cf..05b7f2f856 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -156,7 +156,10 @@ func (m *mockAccountRepoForPlatform) ListSchedulableUngroupedByPlatform(ctx cont func (m *mockAccountRepoForPlatform) ListSchedulableUngroupedByPlatforms(ctx context.Context, platforms []string) ([]Account, error) { return m.ListSchedulableByPlatforms(ctx, platforms) } -func (m *mockAccountRepoForPlatform) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error) { +func (m *mockAccountRepoForPlatform) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error) { + if m.listPlatformFunc != nil { + return m.listPlatformFunc(ctx, firstPlatform(platforms)) + } platformSet := make(map[string]struct{}, len(platforms)) for _, platform := range platforms { platformSet[platform] = struct{}{} diff --git a/backend/internal/service/scheduler_snapshot_batch_query_test.go b/backend/internal/service/scheduler_snapshot_batch_query_test.go index b957891d36..f40384db19 100644 --- a/backend/internal/service/scheduler_snapshot_batch_query_test.go +++ b/backend/internal/service/scheduler_snapshot_batch_query_test.go @@ -56,8 +56,12 @@ func (r *batchAccountQueryRepo) ListSchedulableUngroupedByPlatforms(_ context.Co return r.run(batchAccountQueryKey{platform: platforms[0], mixed: true}) } -func (r *batchAccountQueryRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { - panic("unexpected ListModelAvailabilityCandidates call") +func (r *batchAccountQueryRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + key := batchAccountQueryKey{platform: platforms[0], mixed: len(platforms) > 1} + if groupID != nil { + key.groupID = *groupID + } + return r.run(key) } func (r *batchAccountQueryRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { @@ -725,7 +729,7 @@ type batchQueryBenchmarkRepo struct { accounts []Account } -func (r *batchQueryBenchmarkRepo) ListSchedulableByGroupIDAndPlatform(context.Context, int64, string) ([]Account, error) { +func (r *batchQueryBenchmarkRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { return r.accounts, nil } diff --git a/backend/internal/service/scheduler_snapshot_cancellation_test.go b/backend/internal/service/scheduler_snapshot_cancellation_test.go index 3f46cb14aa..7205624e1b 100644 --- a/backend/internal/service/scheduler_snapshot_cancellation_test.go +++ b/backend/internal/service/scheduler_snapshot_cancellation_test.go @@ -36,7 +36,7 @@ type schedulerCancellationAccountRepo struct { getByIDCalls int } -func (r *schedulerCancellationAccountRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, _ string) ([]Account, error) { +func (r *schedulerCancellationAccountRepo) ListModelAvailabilityCandidates(ctx context.Context, _ *int64, _ []string, _ bool) ([]Account, error) { r.listCalls++ return nil, ctx.Err() } diff --git a/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go b/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go index e4489b81c7..229d29d88a 100644 --- a/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go +++ b/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go @@ -214,8 +214,12 @@ func (r *fullRebuildAccountRepo) ListSchedulableUngroupedByPlatforms(_ context.C return r.record(0, firstPlatform(platforms)) } -func (r *fullRebuildAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { - panic("unexpected ListModelAvailabilityCandidates call") +func (r *fullRebuildAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + var id int64 + if groupID != nil { + id = *groupID + } + return r.record(id, firstPlatform(platforms)) } func (r *fullRebuildAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { diff --git a/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go b/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go index 7eda02f737..bba40e41af 100644 --- a/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go +++ b/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go @@ -296,11 +296,7 @@ func (r *groupLifecycleTestAccountRepo) load(ctx context.Context, platform strin return []Account{{ID: 9001, Platform: platform, Status: StatusActive, Schedulable: true}}, nil } -func (r *groupLifecycleTestAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]Account, error) { - return r.load(ctx, platform) -} - -func (r *groupLifecycleTestAccountRepo) ListSchedulableByGroupIDAndPlatforms(ctx context.Context, _ int64, platforms []string) ([]Account, error) { +func (r *groupLifecycleTestAccountRepo) ListModelAvailabilityCandidates(ctx context.Context, _ *int64, platforms []string, _ bool) ([]Account, error) { platform := "mixed" if len(platforms) > 0 { platform = platforms[0] diff --git a/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go b/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go index 2a476ff077..e4ae7cbb5f 100644 --- a/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go +++ b/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go @@ -108,7 +108,7 @@ type outboxCleanupAccountRepo struct { AccountRepository } -func (r *outboxCleanupAccountRepo) ListSchedulableUngroupedByPlatform(context.Context, string) ([]Account, error) { +func (r *outboxCleanupAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { return nil, nil } diff --git a/backend/internal/service/scheduler_snapshot_retirement_test.go b/backend/internal/service/scheduler_snapshot_retirement_test.go index 7b5a8368d3..5ccc49d524 100644 --- a/backend/internal/service/scheduler_snapshot_retirement_test.go +++ b/backend/internal/service/scheduler_snapshot_retirement_test.go @@ -243,7 +243,8 @@ func TestSchedulerFallbackReturnsDBAccountsWhenBucketRetired(t *testing.T) { cache := newRetirementRaceCache() require.NoError(t, cache.RetireBucket(context.Background(), bucket)) repo := &mockAccountRepoForPlatform{ - accounts: []Account{{ID: 6301, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}}, + accounts: []Account{{ID: 6301, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, + AccountGroups: []AccountGroup{{GroupID: bucket.GroupID}}}}, } svc := NewSchedulerSnapshotService(cache, nil, repo, nil, &config.Config{ RunMode: config.RunModeStandard, diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 2073ad0f53..f49caaa6c0 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -226,7 +226,7 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, if err != nil { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] cache read failed: bucket=%s err=%v", bucket.String(), err) } else if hit { - return derefAccounts(cached), useMixed, nil + return derefSchedulableAccounts(cached), useMixed, nil } token, err := s.cache.CaptureBucketWriteToken(ctx, bucket) if ctxErr := ctx.Err(); ctxErr != nil { @@ -269,7 +269,13 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, } } - return accounts, useMixed, nil + eligible := make([]Account, 0, len(accounts)) + for _, account := range accounts { + if account.IsSchedulable() { + eligible = append(eligible, account) + } + } + return eligible, useMixed, nil } func (s *SchedulerSnapshotService) GetAccount(ctx context.Context, accountID int64) (*Account, error) { @@ -1472,42 +1478,28 @@ func (s *SchedulerSnapshotService) loadAccountsFromDB(ctx context.Context, bucke if s.accountRepo == nil { return nil, ErrSchedulerCacheNotReady } - groupID := bucket.GroupID - if s.isRunModeSimple() { - groupID = 0 + var groupID *int64 + if !s.isRunModeSimple() && bucket.GroupID > 0 { + groupID = &bucket.GroupID } - + platforms := []string{bucket.Platform} if useMixed { - platforms := []string{bucket.Platform, PlatformAntigravity} - var accounts []Account - var err error - if groupID > 0 { - accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatforms(ctx, groupID, platforms) - } else if s.isRunModeSimple() { - accounts, err = s.accountRepo.ListSchedulableByPlatforms(ctx, platforms) - } else { - accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatforms(ctx, platforms) - } - if err != nil { - return nil, err - } - filtered := make([]Account, 0, len(accounts)) - for _, acc := range accounts { - if acc.Platform == PlatformAntigravity && !acc.IsMixedSchedulingEnabled() { - continue - } - filtered = append(filtered, acc) - } - return filtered, nil + platforms = append(platforms, PlatformAntigravity) } - - if groupID > 0 { - return s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, groupID, bucket.Platform) + // Cache the configured pool, as model availability does. Time-based blocks + // must be checked on each read so expiry needs no write or outbox event. + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, groupID, platforms, s.isRunModeSimple()) + if err != nil || !useMixed { + return accounts, err } - if s.isRunModeSimple() { - return s.accountRepo.ListSchedulableByPlatform(ctx, bucket.Platform) + filtered := make([]Account, 0, len(accounts)) + for _, acc := range accounts { + if acc.Platform == PlatformAntigravity && !acc.IsMixedSchedulingEnabled() { + continue + } + filtered = append(filtered, acc) } - return s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, bucket.Platform) + return filtered, nil } func (s *SchedulerSnapshotService) loadAccountsForRebuild( @@ -1654,13 +1646,13 @@ func dedupeBuckets(in []SchedulerBucket) []SchedulerBucket { return out } -func derefAccounts(accounts []*Account) []Account { +func derefSchedulableAccounts(accounts []*Account) []Account { if len(accounts) == 0 { return []Account{} } out := make([]Account, 0, len(accounts)) for _, account := range accounts { - if account == nil { + if account == nil || !account.IsSchedulable() { continue } out = append(out, *account) diff --git a/backend/internal/service/scheduler_snapshot_transient_expiry_test.go b/backend/internal/service/scheduler_snapshot_transient_expiry_test.go index 83cf7516de..888fd013db 100644 --- a/backend/internal/service/scheduler_snapshot_transient_expiry_test.go +++ b/backend/internal/service/scheduler_snapshot_transient_expiry_test.go @@ -41,6 +41,17 @@ type transientExpiryAccountRepo struct { calls int } +func (r *transientExpiryAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { + r.calls++ + var accounts []Account + for _, account := range r.accounts { + if account.IsActive() && account.Schedulable { + accounts = append(accounts, account) + } + } + return accounts, nil +} + // Match the current repository contract: the source query excludes accounts // while any transient cooldown is in the future. func (r *transientExpiryAccountRepo) ListSchedulableByPlatform(context.Context, string) ([]Account, error) { @@ -59,6 +70,7 @@ func TestSchedulerSnapshotRecoversTransientCooldownWithoutIntervalRebuild(t *tes t.Run(field, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { until := time.Now().Add(30 * time.Second) + past := time.Now().Add(-time.Second) ready := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} cooling := ready cooling.ID = 2 @@ -70,7 +82,15 @@ func TestSchedulerSnapshotRecoversTransientCooldownWithoutIntervalRebuild(t *tes case "temp_unschedulable_until": cooling.TempUnschedulableUntil = &until } - repo := &transientExpiryAccountRepo{accounts: []Account{ready, cooling}} + disabled := ready + disabled.ID, disabled.Status = 3, StatusDisabled + manual := ready + manual.ID, manual.Schedulable = 4, false + expired := ready + expired.ID, expired.AutoPauseOnExpired, expired.ExpiresAt = 5, true, &past + expiring := ready + expiring.ID, expiring.AutoPauseOnExpired, expiring.ExpiresAt = 6, true, &until + repo := &transientExpiryAccountRepo{accounts: []Account{ready, cooling, disabled, manual, expired, expiring}} cache := &transientExpirySnapshotCache{} cfg := &config.Config{RunMode: config.RunModeSimple} cfg.Gateway.Scheduling.DbFallbackEnabled = true @@ -87,8 +107,10 @@ func TestSchedulerSnapshotRecoversTransientCooldownWithoutIntervalRebuild(t *tes accounts, _, err := svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) require.NoError(t, err) - require.Equal(t, []int64{1}, eligible(accounts)) + require.Equal(t, []int64{1, 6}, eligible(accounts)) + require.Len(t, accounts, 2, "the DB fallback returns only currently eligible accounts") require.True(t, cache.hit) + require.Len(t, cache.accounts, 4, "the stored pool retains cooling and expired configured members") require.Equal(t, 1, repo.calls) time.Sleep(31 * time.Second) @@ -97,6 +119,8 @@ func TestSchedulerSnapshotRecoversTransientCooldownWithoutIntervalRebuild(t *tes require.NoError(t, err) t.Logf("after expiry: eligible=%v cached_members=%d source_calls=%d", eligible(accounts), len(cache.accounts), repo.calls) assert.ElementsMatch(t, []int64{1, 2}, eligible(accounts), "an expired cooldown must not wait for the interval rebuild") + require.Len(t, accounts, 2, "the cache hit excludes disabled, manually paused and expired accounts") + require.Equal(t, 1, repo.calls, "expiry must not require a database read") // Positive control: a fresh source read immediately restores the account. cache.hit = false From 203de719c3359936579eaff1819ace9b4302000c Mon Sep 17 00:00:00 2001 From: Hato <63497854+Hato626@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:33:01 +0900 Subject: [PATCH 24/85] perf(openai): avoid repeated request copies in OAuth metadata cleanup --- .../service/openai_gateway_request_body.go | 47 +++++--- .../openai_oauth_input_metadata_test.go | 100 ++++++++++++++++++ 2 files changed, 132 insertions(+), 15 deletions(-) diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b7e4514405..4f1bf2d85f 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1452,9 +1452,9 @@ func normalizeOpenAIOAuthResponsesCompatibilityBody(body []byte) ([]byte, bool, } normalized := body changed := false - prompt := gjson.GetBytes(normalized, "prompt") + prompt := parseRawJSONView(normalized).Get("prompt") if prompt.Exists() { - input := gjson.GetBytes(normalized, "input") + input := parseRawJSONView(normalized).Get("input") if prompt.Type != gjson.Null && (!input.Exists() || input.Type == gjson.Null) { next, err := sjson.SetRawBytes(normalized, "input", []byte(prompt.Raw)) if err != nil { @@ -1469,7 +1469,7 @@ func normalizeOpenAIOAuthResponsesCompatibilityBody(body []byte) ([]byte, bool, normalized = next changed = true } - if gjson.GetBytes(normalized, "commands").Exists() { + if parseRawJSONView(normalized).Get("commands").Exists() { next, err := sjson.DeleteBytes(normalized, "commands") if err != nil { return body, false, fmt.Errorf("normalize oauth responses delete commands: %w", err) @@ -1478,22 +1478,39 @@ func normalizeOpenAIOAuthResponsesCompatibilityBody(body []byte) ([]byte, bool, changed = true } // Only remove the input-item field, never same-named user content. - input := gjson.GetBytes(normalized, "input") + input := parseRawJSONView(normalized).Get("input") if !input.IsArray() { return normalized, changed, nil } - for i, item := range input.Array() { - if !item.IsObject() || !item.Get("internal_chat_message_metadata_passthrough").Exists() { - continue - } - next, err := sjson.DeleteBytes(normalized, fmt.Sprintf("input.%d.internal_chat_message_metadata_passthrough", i)) - if err != nil { - return body, false, fmt.Errorf("normalize oauth input metadata: %w", err) - } - normalized = next - changed = true + const field = "internal_chat_message_metadata_passthrough" + hasMetadata := false + input.ForEach(func(_, item gjson.Result) bool { + hasMetadata = item.IsObject() && item.Get(field).Exists() + return !hasMetadata + }) + if !hasMetadata { + return normalized, changed, nil } - return normalized, changed, nil + + // Clean each item locally, then rebuild the request once. Deleting by + // input.N on the full body copies the entire history for every message. + var items []string + var normalizeErr error + input.ForEach(func(_, item gjson.Result) bool { + raw := item.Raw + if item.IsObject() && item.Get(field).Exists() { + raw, normalizeErr = sjson.Delete(raw, field) + if normalizeErr != nil { + return false + } + } + items = append(items, raw) + return true + }) + if normalizeErr != nil { + return body, false, fmt.Errorf("normalize oauth input metadata: %w", normalizeErr) + } + return replaceOpenAIRawInput(normalized, input, items), true, nil } func normalizeGPT6ResponsesSampling(body []byte, model string) ([]byte, bool, error) { diff --git a/backend/internal/service/openai_oauth_input_metadata_test.go b/backend/internal/service/openai_oauth_input_metadata_test.go index 0279ee6112..d6c36bcf5d 100644 --- a/backend/internal/service/openai_oauth_input_metadata_test.go +++ b/backend/internal/service/openai_oauth_input_metadata_test.go @@ -1,13 +1,113 @@ package service import ( + "bytes" "encoding/json" + "runtime" + "strings" "testing" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" ) +func oauthInputMetadataHistory(items, textBytes, metadataEvery int) []byte { + var body strings.Builder + body.WriteString(`{"model":"gpt-5.5","opaque":9007199254740993,"input":[`) + text := strings.Repeat("x", textBytes) + for i := 0; i < items; i++ { + if i > 0 { + body.WriteByte(',') + } + body.WriteString(`{"role":"user","content":"`) + body.WriteString(text) + body.WriteByte('"') + if metadataEvery > 0 && i%metadataEvery == 0 { + body.WriteString(`,"internal_chat_message_metadata_passthrough":{"content_item_kinds":["text"]}`) + } + body.WriteByte('}') + } + body.WriteString(`],"tail":{"keep":true}}`) + return []byte(body.String()) +} + +func TestOAuthInputInternalMetadataLargeHistory(t *testing.T) { + for _, fixture := range []struct { + name string + metadataEvery int + }{ + {name: "all", metadataEvery: 1}, + {name: "sparse", metadataEvery: 32}, + } { + t.Run(fixture.name, func(t *testing.T) { + body := oauthInputMetadataHistory(128, 16<<10, fixture.metadataEvery) + original := bytes.Clone(body) + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody(body) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, original, body, "normalization must not mutate caller-owned history") + require.True(t, gjson.ValidBytes(out)) + require.Equal(t, int64(128), gjson.GetBytes(out, "input.#").Int()) + require.NotContains(t, string(out), "internal_chat_message_metadata_passthrough") + require.Equal(t, "9007199254740993", gjson.GetBytes(out, "opaque").Raw) + require.True(t, gjson.GetBytes(out, "tail.keep").Bool()) + text := strings.Repeat("x", 16<<10) + for _, item := range gjson.GetBytes(out, "input").Array() { + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, text, item.Get("content").String()) + } + }) + } +} + +func TestOAuthInputInternalMetadataPreservesRawContent(t *testing.T) { + const body = ` {"opaque":9007199254740993,"inpu\u0074":[null,42,"keep",{"type":"function_call_output","call_id":"call_keep","output":[{"type":"input_image","image_url":"https://example.com/image.png","internal_chat_message_metadata_passthrough":{"keep":true}}],"internal_chat_message_metadata_passthrou\u0067h":null},{"role":"user","content":"internal_chat_message_metadata_passthrough"}],"tail" : "unchanged" } ` + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody([]byte(body)) + require.NoError(t, err) + require.True(t, changed) + require.True(t, bytes.HasPrefix(out, []byte(` {"opaque":9007199254740993,"inpu\u0074":`))) + require.True(t, bytes.HasSuffix(out, []byte(`,"tail" : "unchanged" } `))) + require.Equal(t, `[null,42,"keep",{"type":"function_call_output","call_id":"call_keep","output":[{"type":"input_image","image_url":"https://example.com/image.png","internal_chat_message_metadata_passthrough":{"keep":true}}]},{"role":"user","content":"internal_chat_message_metadata_passthrough"}]`, gjson.GetBytes(out, "input").Raw) +} + +func TestOAuthInputInternalMetadataUnchangedHistory(t *testing.T) { + body := oauthInputMetadataHistory(128, 16<<10, 0) + original := bytes.Clone(body) + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody(body) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, original, out) + require.Same(t, &body[0], &out[0], "unchanged history should retain the caller's buffer") +} + +func BenchmarkOAuthInputInternalMetadataHistory(b *testing.B) { + for _, fixture := range []struct { + name string + items int + metadataEvery int + }{ + {name: "1_item", items: 1, metadataEvery: 1}, + {name: "32_items", items: 32, metadataEvery: 1}, + {name: "128_items", items: 128, metadataEvery: 1}, + {name: "128_items_sparse", items: 128, metadataEvery: 32}, + {name: "128_items_unchanged", items: 128}, + } { + b.Run(fixture.name, func(b *testing.B) { + body := oauthInputMetadataHistory(fixture.items, 16<<10, fixture.metadataEvery) + b.ReportAllocs() + b.SetBytes(int64(len(body))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody(body) + if err != nil || changed != (fixture.metadataEvery > 0) { + b.Fatalf("changed=%v err=%v", changed, err) + } + runtime.KeepAlive(out) + } + }) + } +} + func TestOAuthInputInternalMetadata(t *testing.T) { const field = "internal_chat_message_metadata_passthrough" // The identically named field in user content must not be recursively stripped. From 97705d147edef9ae673b2c0bd200b9f8b0558b7a Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:43:27 -0800 Subject: [PATCH 25/85] fix(accounts): reject wildcard model whitelist entries Prevent adding models with wildcard characters and show an info message. --- frontend/src/components/account/ModelWhitelistSelector.vue | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index b1645a49fa..16788af018 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -278,6 +278,10 @@ const copyModelId = async (model: string) => { const addCustom = () => { const model = customModel.value.trim() if (!model) return + if (model.includes('*')) { + appStore.showInfo(t('admin.accounts.modelWildcardNotSupported')) + return + } if (props.modelValue.includes(model)) { appStore.showInfo(t('admin.accounts.modelExists')) return From 24d77b3306385e2ccb2d3336b3ea1a4aad4cb438 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:45:09 -0800 Subject: [PATCH 26/85] Add English whitelist validation hint --- frontend/src/i18n/locales/en/admin/accounts.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 78f7c550dd..e851568a40 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -857,6 +857,7 @@ export default { enterCustomModelName: 'Enter custom model name', addModel: 'Add', modelExists: 'Model already exists', + modelWildcardNotSupported: 'Wildcards are not supported in the model whitelist. Enter an exact model name.', modelMappingConflict: 'A mapping already exists for {from} → {to}. Modify or remove it under Model Mapping before adding this whitelist model', modelCount: '{count} models', poolMode: 'Pool Mode', From 346a7dac0261416e5cb1edc05317f68796417020 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:45:43 -0800 Subject: [PATCH 27/85] Add Chinese whitelist validation hint --- frontend/src/i18n/locales/zh/admin/accounts.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index e55b725e96..4c93b07972 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -968,6 +968,7 @@ export default { enterCustomModelName: '输入自定义模型名称', addModel: '填入', modelExists: '该模型已存在', + modelWildcardNotSupported: '模型白名单不支持通配符,请输入完整的模型名称。', modelMappingConflict: '该模型已配置映射 {from} → {to},请在模型映射中修改或删除后再添加白名单模型', modelCount: '{count} 个模型', poolMode: '池模式', From 7e75ee4b65f56fadce41b093c106c33c6663b12e Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:46:13 -0800 Subject: [PATCH 28/85] Cover wildcard rejection and corrected model input --- .../__tests__/ModelWhitelistSelector.spec.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts index 83f843df73..277fdd4780 100644 --- a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts +++ b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts @@ -165,6 +165,33 @@ describe('ModelWhitelistSelector', () => { wrapper.unmount() }) + it.each(['claude-*', '*', 'gpt-*-mini'])( + 'rejects wildcard whitelist entry %s without clearing the input', async (model) => { + const wrapper = mountSelector({ modelValue: ['gpt-5'] }) + const input = wrapper.get('input[placeholder="admin.accounts.enterCustomModelName"]') + await input.setValue(model) + await wrapper.findAll('button').find(button => button.text() === 'admin.accounts.addModel')!.trigger('click') + + expect(wrapper.emitted('update:modelValue')).toBeUndefined() + expect(showInfo).toHaveBeenCalledWith('admin.accounts.modelWildcardNotSupported') + expect((input.element as HTMLInputElement).value).toBe(model) + } + ) + + it('rejects wildcard entries submitted with Enter and accepts a corrected exact model', async () => { + const wrapper = mountSelector() + const input = wrapper.get('input[placeholder="admin.accounts.enterCustomModelName"]') + await input.setValue(' claude-* ') + await input.trigger('keydown.enter') + expect(wrapper.emitted('update:modelValue')).toBeUndefined() + expect(showInfo).toHaveBeenCalledWith('admin.accounts.modelWildcardNotSupported') + + await input.setValue(' claude-sonnet-4-5 ') + await input.trigger('keydown.enter') + expect(wrapper.emitted('update:modelValue')).toEqual([[['claude-sonnet-4-5']]]) + expect((input.element as HTMLInputElement).value).toBe('') + }) + it('rejects a custom whitelist model that is already mapped to a different target', async () => { const wrapper = mountSelector({ modelMappings: [{ from: 'gpt-latest', to: 'deepseek-chat' }] }) await wrapper.get('input[placeholder="admin.accounts.enterCustomModelName"]').setValue(' gpt-latest ') From b0f6f8391153ee4ce6753d1733ab54a1c2c81b71 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 08:46:51 -0800 Subject: [PATCH 29/85] fix(claude): recover requests after concurrent token rotation --- backend/internal/service/gateway_forward.go | 42 ++++ .../gateway_forward_as_chat_completions.go | 49 ++-- .../service/gateway_forward_as_responses.go | 49 ++-- .../service/gateway_rotated_token_test.go | 214 ++++++++++++++++++ 4 files changed, 318 insertions(+), 36 deletions(-) create mode 100644 backend/internal/service/gateway_rotated_token_test.go diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index c74472ce1b..17ce62faa3 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -53,6 +53,37 @@ func (s *GatewayService) shouldFailoverUpstreamError(statusCode int) bool { } } +// rotatedClaudeAccessToken recovers a token rotated while this request was in +// flight. Compare against the token actually sent, which may have come from the +// cache rather than the account snapshot. Never refresh or persist credentials +// here: an unchanged token must retain the normal 401 policy. +func (s *GatewayService) rotatedClaudeAccessToken(ctx context.Context, account *Account, rejectedToken string) string { + if account == nil || account.Platform != PlatformAnthropic || account.Type != AccountTypeOAuth || + s.accountRepo == nil || rejectedToken == "" || ctx.Err() != nil { + return "" + } + latest, err := s.accountRepo.GetByID(ctx, account.ID) + if err != nil { + slog.Warn("claude_oauth_401_reload_failed", "account_id", account.ID, "error", err) + return "" + } + if latest == nil || latest.Platform != PlatformAnthropic || latest.Type != AccountTypeOAuth || + latest.Status != StatusActive || !latest.Schedulable { + return "" + } + token := strings.TrimSpace(latest.GetCredential("access_token")) + if token == "" || token == rejectedToken { + return "" + } + if p := s.claudeTokenProvider; p != nil && p.tokenCache != nil { + if err := p.tokenCache.DeleteAccessToken(ctx, ClaudeTokenCacheKey(latest)); err != nil { + slog.Warn("claude_oauth_401_invalidate_cache_failed", "account_id", account.ID, "error", err) + } + } + slog.Info("claude_oauth_rotated_token_retry", "account_id", account.ID) + return token +} + func retryBackoffDelay(attempt int) time.Duration { // attempt 从 1 开始,表示第 attempt 次请求刚失败,需要等待后进行第 attempt+1 次请求。 if attempt <= 0 { @@ -387,6 +418,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A var resp *http.Response lastWireBody := body retryStart := time.Now() + retriedRotatedToken := false for attempt := 1; attempt <= maxRetryAttempts; attempt++ { // 构建上游请求(每次重试需要重新构建,因为请求体需要重新读取) upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) @@ -409,6 +441,16 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A }) } + if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken && + attempt < maxRetryAttempts && time.Since(retryStart) < maxRetryElapsed { + if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" { + _ = resp.Body.Close() + token = rotatedToken + retriedRotatedToken = true + continue + } + } + // 优先检测thinking block签名错误(400)并重试一次 if resp.StatusCode == 400 { respBody, readErr := s.readUpstreamErrorBody(resp) diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index a1f9786719..ebbc7894a9 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -122,30 +122,43 @@ func (s *GatewayService) ForwardAsChatCompletions( proxyURL = account.Proxy.URL() } - // 10. Build upstream request - upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) - upstreamReq, forwardedBody, err := s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) - releaseUpstreamCtx() - if err != nil { - return nil, fmt.Errorf("build upstream request: %w", err) + // 10. Build and send the request, recovering a concurrent token rotation once. + var upstreamReq *http.Request + var forwardedBody []byte + var resp *http.Response + for retriedRotatedToken := false; ; { + upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) + upstreamReq, forwardedBody, err = s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) + releaseUpstreamCtx() + if err != nil { + return nil, fmt.Errorf("build upstream request: %w", err) + } + resp, err = s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ + UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), + }) + } + if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken { + if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" { + _ = resp.Body.Close() + token = rotatedToken + retriedRotatedToken = true + continue + } + } + break } + defer func() { _ = resp.Body.Close() }() + // Bill the final Anthropic effort after conversion and account normalization. // For example, OpenAI xhigh is forwarded as output_config.effort=max. reasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(forwardedBody, "output_config.effort").String()) reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, forwardedBody, mappedModel) - // 11. Send request - resp, err := s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) - if err != nil { - if resp != nil && resp.Body != nil { - _ = resp.Body.Close() - } - return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ - UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), - }) - } - defer func() { _ = resp.Body.Close() }() - // 12. Handle error response with failover if resp.StatusCode >= 400 { respBody, _ := s.readUpstreamErrorBody(resp) diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index db10be2568..f4055ddb4d 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -133,30 +133,43 @@ func (s *GatewayService) ForwardAsResponses( proxyURL = account.Proxy.URL() } - // 10. Build upstream request - upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) - upstreamReq, forwardedBody, err := s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) - releaseUpstreamCtx() - if err != nil { - return nil, fmt.Errorf("build upstream request: %w", err) + // 10. Build and send the request, recovering a concurrent token rotation once. + var upstreamReq *http.Request + var forwardedBody []byte + var resp *http.Response + for retriedRotatedToken := false; ; { + upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) + upstreamReq, forwardedBody, err = s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) + releaseUpstreamCtx() + if err != nil { + return nil, fmt.Errorf("build upstream request: %w", err) + } + resp, err = s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ + UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), + }) + } + if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken { + if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" { + _ = resp.Body.Close() + token = rotatedToken + retriedRotatedToken = true + continue + } + } + break } + defer func() { _ = resp.Body.Close() }() + // Bill the final Anthropic effort after conversion and account normalization. // For example, OpenAI xhigh is forwarded as output_config.effort=max. reasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(forwardedBody, "output_config.effort").String()) reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, forwardedBody, mappedModel) - // 11. Send request - resp, err := s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) - if err != nil { - if resp != nil && resp.Body != nil { - _ = resp.Body.Close() - } - return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ - UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), - }) - } - defer func() { _ = resp.Body.Close() }() - // 12. Handle error response with failover if resp.StatusCode >= 400 { respBody, _ := s.readUpstreamErrorBody(resp) diff --git a/backend/internal/service/gateway_rotated_token_test.go b/backend/internal/service/gateway_rotated_token_test.go new file mode 100644 index 0000000000..41a799d44f --- /dev/null +++ b/backend/internal/service/gateway_rotated_token_test.go @@ -0,0 +1,214 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type rotatedClaudeTokenRepo struct { + AccountRepository + account *Account + err error + reads int + cooldownCalls int + errorCalls int +} + +func (r *rotatedClaudeTokenRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.reads++ + return r.account, r.err +} + +func (r *rotatedClaudeTokenRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error { + r.cooldownCalls++ + return nil +} + +func (r *rotatedClaudeTokenRepo) SetError(context.Context, int64, string) error { + r.errorCalls++ + return nil +} + +type rotatedClaudeTokenBody struct { + io.Reader + closed bool +} + +func (b *rotatedClaudeTokenBody) Close() error { + b.closed = true + return nil +} + +func TestGatewayService_RotatedClaudeToken(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, path := range []string{"messages", "chat/completions", "responses"} { + for _, stream := range []bool{false, true} { + for _, tc := range []struct { + name string + snapshotToken string + storedToken string + lookupErr error + accountType string + inactive bool + unschedulable bool + cacheDeleteErr error + rejectRetry bool + wantCalls int + wantCooldown int + wantError int + }{ + {name: "rotated", storedToken: "new-token", wantCalls: 2}, + {name: "cached_token_differs_from_snapshot", snapshotToken: "new-token", storedToken: "new-token", wantCalls: 2}, + {name: "unchanged", storedToken: "old-token", wantCalls: 1, wantCooldown: 1}, + {name: "missing", wantCalls: 1, wantCooldown: 1}, + {name: "lookup_failed", lookupErr: errors.New("database unavailable"), wantCalls: 1, wantCooldown: 1}, + {name: "retry_rejected", storedToken: "new-token", rejectRetry: true, wantCalls: 2, wantCooldown: 1}, + {name: "disabled_account", storedToken: "new-token", inactive: true, wantCalls: 1, wantCooldown: 1}, + {name: "unschedulable_account", storedToken: "new-token", unschedulable: true, wantCalls: 1, wantCooldown: 1}, + {name: "cache_delete_failed", storedToken: "new-token", cacheDeleteErr: errors.New("cache unavailable"), wantCalls: 2}, + {name: "setup_token", accountType: AccountTypeSetupToken, storedToken: "new-token", wantCalls: 1, wantError: 1}, + {name: "api_key", accountType: AccountTypeAPIKey, storedToken: "new-token", wantCalls: 1, wantError: 1}, + } { + t.Run(fmt.Sprintf("%s/stream=%t/%s", path, stream, tc.name), func(t *testing.T) { + snapshotToken := tc.snapshotToken + if snapshotToken == "" { + snapshotToken = "old-token" + } + account := &Account{ + ID: 71, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"access_token": snapshotToken, "refresh_token": "refresh-token", "api_key": "old-token"}, + } + if tc.accountType != "" { + account.Type = tc.accountType + } + latest := *account + latest.Credentials = map[string]any{"access_token": tc.storedToken, "refresh_token": "new-refresh-token"} + if tc.inactive { + latest.Status = StatusError + } + if tc.unschedulable { + latest.Schedulable = false + } + repo := &rotatedClaudeTokenRepo{account: account} + cache := newClaudeTokenCacheStub() + cache.deleteErr = tc.cacheDeleteErr + require.NoError(t, cache.SetAccessToken(context.Background(), ClaudeTokenCacheKey(account), "old-token", time.Hour)) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}} + calls := 0 + var firstWireBody []byte + var rejectedBodies []*rotatedClaudeTokenBody + upstream := &systemOneHTTPUpstream{do: func(req *http.Request) (*http.Response, error) { + calls++ + wireBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + _ = req.Body.Close() + if calls == 1 { + if account.Type == AccountTypeAPIKey { + require.Equal(t, "old-token", getHeaderRaw(req.Header, "x-api-key")) + } else { + require.Equal(t, "Bearer old-token", getHeaderRaw(req.Header, "authorization")) + } + firstWireBody = wireBody + // The refresh completes only after the rejected request was sent. + repo.account, repo.err = &latest, tc.lookupErr + } else { + require.Equal(t, 2, calls, "recover at most once, even if the token rotates again") + require.Equal(t, "Bearer new-token", getHeaderRaw(req.Header, "authorization")) + require.Equal(t, firstWireBody, wireBody, "replay the complete request") + require.True(t, rejectedBodies[0].closed) + latest.Credentials["access_token"] = "third-token" + } + if calls == 1 || tc.rejectRetry { + body := &rotatedClaudeTokenBody{Reader: strings.NewReader(`{"type":"error","error":{"type":"authentication_error","message":"OAuth access token has been revoked"}}`)} + rejectedBodies = append(rejectedBodies, body) + return &http.Response{StatusCode: http.StatusUnauthorized, Header: make(http.Header), Body: body}, nil + } + payload := strings.Join([]string{ + "event: message_start", + `data: {"type":"message_start","message":{"id":"msg_rotated","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[],"usage":{"input_tokens":11}}}`, + "", "event: content_block_start", + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + "", "event: content_block_delta", + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}`, + "", "event: content_block_stop", + `data: {"type":"content_block_stop","index":0}`, + "", "event: message_delta", + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}`, + "", "event: message_stop", `data: {"type":"message_stop"}`, "", "", + }, "\n") + contentType := "text/event-stream" + if path == "messages" && !stream { + payload = `{"id":"msg_rotated","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"input_tokens":11,"output_tokens":7}}` + contentType = "application/json" + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))}, nil + }} + svc := &GatewayService{ + cfg: cfg, accountRepo: repo, httpUpstream: upstream, + claudeTokenProvider: NewClaudeTokenProvider(repo, cache, nil), + rateLimitService: &RateLimitService{cfg: cfg, accountRepo: repo}, + deferredService: &DeferredService{}, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+path, nil) + body := []byte(fmt.Sprintf(`{"model":"claude-sonnet-4-6","stream":%t,"max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`, stream)) + var result *ForwardResult + var err error + switch path { + case "messages": + var parsed *ParsedRequest + parsed, err = ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + result, err = svc.Forward(context.Background(), c, account, parsed) + case "chat/completions": + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + case "responses": + body = []byte(fmt.Sprintf(`{"model":"claude-sonnet-4-6","stream":%t,"input":"hello"}`, stream)) + result, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + } + if tc.wantCooldown == 0 && tc.wantError == 0 { + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 11, result.Usage.InputTokens) + require.Equal(t, 7, result.Usage.OutputTokens) + require.Contains(t, rec.Body.String(), "hello") + require.NotContains(t, rec.Body.String(), "revoked") + cached, cacheErr := cache.GetAccessToken(context.Background(), ClaudeTokenCacheKey(account)) + require.NoError(t, cacheErr) + if tc.cacheDeleteErr == nil { + require.NotEqual(t, "old-token", cached) + } + } else { + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.Equal(t, http.StatusUnauthorized, failover.StatusCode) + require.False(t, c.Writer.Written(), "leave the response available for account failover") + } + require.Equal(t, tc.wantCalls, calls) + require.Equal(t, tc.wantCooldown, repo.cooldownCalls) + require.Equal(t, tc.wantError, repo.errorCalls) + require.Equal(t, snapshotToken, account.GetCredential("access_token"), "do not mutate the shared account snapshot") + require.Equal(t, "new-refresh-token", latest.GetCredential("refresh_token"), "do not overwrite rotated credentials") + for _, body := range rejectedBodies { + require.True(t, body.closed) + } + }) + } + } + } +} From 4f8e9ae2f188f856266be7086d370988004a3faf Mon Sep 17 00:00:00 2001 From: Hato <63497854+Hato626@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:14:42 +0900 Subject: [PATCH 30/85] test(openai): handle metadata fixture builder return values --- .../service/openai_oauth_input_metadata_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/backend/internal/service/openai_oauth_input_metadata_test.go b/backend/internal/service/openai_oauth_input_metadata_test.go index d6c36bcf5d..d234831684 100644 --- a/backend/internal/service/openai_oauth_input_metadata_test.go +++ b/backend/internal/service/openai_oauth_input_metadata_test.go @@ -13,21 +13,21 @@ import ( func oauthInputMetadataHistory(items, textBytes, metadataEvery int) []byte { var body strings.Builder - body.WriteString(`{"model":"gpt-5.5","opaque":9007199254740993,"input":[`) + _, _ = body.WriteString(`{"model":"gpt-5.5","opaque":9007199254740993,"input":[`) text := strings.Repeat("x", textBytes) for i := 0; i < items; i++ { if i > 0 { - body.WriteByte(',') + _ = body.WriteByte(',') } - body.WriteString(`{"role":"user","content":"`) - body.WriteString(text) - body.WriteByte('"') + _, _ = body.WriteString(`{"role":"user","content":"`) + _, _ = body.WriteString(text) + _ = body.WriteByte('"') if metadataEvery > 0 && i%metadataEvery == 0 { - body.WriteString(`,"internal_chat_message_metadata_passthrough":{"content_item_kinds":["text"]}`) + _, _ = body.WriteString(`,"internal_chat_message_metadata_passthrough":{"content_item_kinds":["text"]}`) } - body.WriteByte('}') + _ = body.WriteByte('}') } - body.WriteString(`],"tail":{"keep":true}}`) + _, _ = body.WriteString(`],"tail":{"keep":true}}`) return []byte(body.String()) } From 849aa593d4ac56519e8b5fb98fb7031d3cbe0d43 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 09:14:56 -0800 Subject: [PATCH 31/85] fix(cn-quota): refresh usage cells with account snapshots --- .../account/CNProviderQuotaCell.vue | 34 ++++++-- .../__tests__/CNProviderQuotaCell.spec.ts | 82 +++++++++++++++++++ 2 files changed, 107 insertions(+), 9 deletions(-) diff --git a/frontend/src/components/account/CNProviderQuotaCell.vue b/frontend/src/components/account/CNProviderQuotaCell.vue index d814173abb..9cddb9f088 100644 --- a/frontend/src/components/account/CNProviderQuotaCell.vue +++ b/frontend/src/components/account/CNProviderQuotaCell.vue @@ -4,7 +4,7 @@ data-test="cn-provider-quota" class="min-w-[220px] space-y-1" > -
cnQuotaCellVisible(props.account)) const loading = ref(false) const error = ref(null) -const data = ref(null) +const probeData = ref(null) +let probeGeneration = 0 // 后端周期任务/手动探测写入的 extra 快照键(_ 前缀,与后端 // cnQuotaExtraUpdates 对齐)。页面加载即有数据,无需等待探测。 @@ -118,6 +119,18 @@ const snapshotData = computed(() => { return { success: true, tiers } as CNProviderQuotaProbeResult }) +const data = computed(() => probeData.value ?? snapshotData.value) + +// A list refresh replaces account.extra even when its quota snapshot is +// unchanged. Keep a manual probe until the quota values or snapshot version +// actually change, rather than reverting it on unrelated account updates. +watch( + [snapshotData, () => readExtraString(`${props.account.platform}_usage_updated_at`)], + (next, previous) => { + if (JSON.stringify(next) !== JSON.stringify(previous)) probeData.value = null + } +) + // 快照是否过期(无更新时间或超过 staleness 窗口)→ 挂载时需要自动探测。 const snapshotIsStale = computed(() => { const updatedAt = readExtraString(`${props.account.platform}_usage_updated_at`) @@ -130,7 +143,6 @@ const snapshotIsStale = computed(() => { // 避免静默失败导致单元格空白无提示)。 onMounted(() => { if (!visible.value) return - data.value = snapshotData.value if (!snapshotIsStale.value) return // 模块级去抖:列表页每行一个实例,翻页/筛选/刷新会重复挂载;同一账号 // 短时间内已自动探测过则跳过,避免对上游形成探测风暴。 @@ -168,27 +180,31 @@ const windowLabel = (window: string) => { const handleProbe = async () => { if (loading.value) return + const generation = ++probeGeneration + const accountID = props.account.id loading.value = true error.value = null try { - const result = await adminAPI.cnProviders.queryQuota(props.account.id) + const result = await adminAPI.cnProviders.queryQuota(accountID) + if (generation !== probeGeneration) return // 失败时保留已渲染的快照条形图(仅显示错误行),成功才覆盖。 if (result.success) { - data.value = result + probeData.value = result } else { error.value = result.error || t('common.error') } } catch (e) { - error.value = extractErrorMessage(e) + if (generation === probeGeneration) error.value = extractErrorMessage(e) } finally { - loading.value = false + if (generation === probeGeneration) loading.value = false } } watch( - () => props.account.id, + [() => props.account.id, () => props.account.platform], () => { - data.value = null + probeGeneration++ + probeData.value = null error.value = null loading.value = false } diff --git a/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts b/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts index e0384fe72c..55c250dbd1 100644 --- a/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts +++ b/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts @@ -1,5 +1,6 @@ import { flushPromises, mount } from '@vue/test-utils' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reactive } from 'vue' import CNProviderQuotaCell from '../CNProviderQuotaCell.vue' import UsageProgressBar from '../UsageProgressBar.vue' import type { Account } from '@/types' @@ -102,4 +103,85 @@ describe('CNProviderQuotaCell', () => { await flushPromises() expect(queryQuota).toHaveBeenCalledWith(account.id) }) + + it('renders replacement quota values and windows for the same account without probing', async () => { + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.setProps({ account: { + ...account, + extra: { + ...account.extra, + zhipu_5h_used_percent: 52, + zhipu_weekly_used_percent: null, + zhipu_monthly_used_percent: 81, + zhipu_monthly_reset_at: '2026-12-01T00:00:00Z' + } + } }) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars.map(bar => bar.props('utilization'))).toEqual([52, 81]) + expect(bars[1].props('label')).toBe('admin.accounts.cnProviders.windowMonthly') + expect(bars[1].props('resetsAt')).toBe('2026-12-01T00:00:00Z') + expect(queryQuota).not.toHaveBeenCalled() + }) + + it('reacts to quota changes inside the existing extra object', async () => { + const row = reactive({ ...account, extra: { ...account.extra } }) + const wrapper = mount(CNProviderQuotaCell, { props: { account: row } }) + row.extra.zhipu_5h_used_percent = 63 + await flushPromises() + expect(wrapper.findAllComponents(UsageProgressBar)[0].props('utilization')).toBe(63) + expect(queryQuota).not.toHaveBeenCalled() + }) + + it('removes bars when a refreshed snapshot clears all quota windows', async () => { + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.setProps({ account: { + ...account, + extra: { ...account.extra, zhipu_5h_used_percent: null, zhipu_weekly_used_percent: null } + } }) + expect(wrapper.findAllComponents(UsageProgressBar)).toHaveLength(0) + expect(queryQuota).not.toHaveBeenCalled() + }) + + it('keeps a manual result through unrelated refreshes, then adopts a changed snapshot', async () => { + queryQuota.mockResolvedValue({ success: true, tiers: [{ window: '5h', used_percent: 44 }] }) + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.get('[data-test="cn-provider-quota-probe"]').trigger('click') + await flushPromises() + await wrapper.setProps({ account: { + ...account, extra: { ...account.extra, unrelated_field: true } + } }) + expect(wrapper.findAllComponents(UsageProgressBar).map(bar => bar.props('utilization'))).toEqual([44]) + await wrapper.setProps({ account: { + ...account, extra: { ...account.extra, zhipu_5h_used_percent: 66 } + } }) + expect(wrapper.findAllComponents(UsageProgressBar).map(bar => bar.props('utilization'))).toEqual([66, 27]) + expect(queryQuota).toHaveBeenCalledTimes(1) + }) + + it('adopts a new snapshot version even if its quota values equal the old snapshot', async () => { + queryQuota.mockResolvedValue({ success: true, tiers: [{ window: '5h', used_percent: 44 }] }) + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.get('[data-test="cn-provider-quota-probe"]').trigger('click') + await flushPromises() + await wrapper.setProps({ account: { + ...account, + extra: { ...account.extra, zhipu_usage_updated_at: new Date(Date.now() + 1000).toISOString() } + } }) + expect(wrapper.findAllComponents(UsageProgressBar).map(bar => bar.props('utilization'))).toEqual([0, 27]) + }) + + it('keeps the new account snapshot when the previous account probe finishes late', async () => { + let resolveProbe!: (value: unknown) => void + queryQuota.mockReturnValue(new Promise(resolve => { resolveProbe = resolve })) + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.get('[data-test="cn-provider-quota-probe"]').trigger('click') + await wrapper.setProps({ account: { + ...account, id: 8, extra: { ...account.extra, zhipu_5h_used_percent: 91 } + } }) + expect(wrapper.findAllComponents(UsageProgressBar)[0].props('utilization')).toBe(91) + resolveProbe({ success: true, tiers: [{ window: '5h', used_percent: 44 }] }) + await flushPromises() + expect(wrapper.findAllComponents(UsageProgressBar)[0].props('utilization')).toBe(91) + expect(wrapper.get('[data-test="cn-provider-quota-probe"]').attributes('disabled')).toBeUndefined() + }) }) From e95e9eb748b9eb2c2abd90abc8f4b7c5d73f3b11 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 09:20:16 -0800 Subject: [PATCH 32/85] test(cn-quota): include snapshot regressions in critical CI --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index 4a853cefdd..df5b97fb8b 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ FRONTEND_CRITICAL_VITEST := \ src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \ src/constants/__tests__/platforms.spec.ts \ src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \ + src/components/account/__tests__/CNProviderQuotaCell.spec.ts \ src/components/account/__tests__/CreateAccountModal.spec.ts \ src/components/account/__tests__/EditAccountModal.spec.ts \ src/components/account/__tests__/credentialsBuilder.spec.ts \ From d850b8e3a25ce1e19d9e6c23965344000927a4bd Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 10:15:59 -0800 Subject: [PATCH 33/85] fix(gateway): enforce effort policies on Anthropic compatibility routes --- .../gateway_compat_effort_policy_test.go | 163 ++++++++++++++++++ .../gateway_handler_chat_completions.go | 6 + .../handler/gateway_handler_responses.go | 6 + 3 files changed, 175 insertions(+) create mode 100644 backend/internal/handler/gateway_compat_effort_policy_test.go diff --git a/backend/internal/handler/gateway_compat_effort_policy_test.go b/backend/internal/handler/gateway_compat_effort_policy_test.go new file mode 100644 index 0000000000..3f13c33da0 --- /dev/null +++ b/backend/internal/handler/gateway_compat_effort_policy_test.go @@ -0,0 +1,163 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type compatEffortPolicyUpstream struct { + service.HTTPUpstream + bodies [][]byte +} + +func (u *compatEffortPolicyUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + u.bodies = append(u.bodies, body) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)), + }, nil +} + +func TestGatewayCompatibilityHandlersReasoningEffortPolicy(t *testing.T) { + gin.SetMode(gin.TestMode) + const model = "claude-sonnet-4.5" + for _, endpoint := range []string{"chat/completions", "responses"} { + for _, platform := range []string{service.PlatformAnthropic, service.PlatformComposite} { + for _, stream := range []bool{false, true} { + for _, tc := range []struct { + name string + effort string + ceiling string + overLimit string + mappings []service.ReasoningEffortMapping + want string + denied bool + }{ + {name: "ceiling", effort: "high", ceiling: "medium", want: "medium"}, + {name: "mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low"}}, want: "low"}, + {name: "mapping then ceiling", effort: "low", ceiling: "medium", mappings: []service.ReasoningEffortMapping{{From: "low", To: "high"}}, want: "medium"}, + {name: "model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: model}}, want: "low"}, + {name: "other model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: "other-model"}}, want: "high"}, + {name: "deny ceiling", effort: "high", ceiling: "medium", overLimit: service.ReasoningEffortOverLimitDeny, denied: true}, + {name: "deny mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "deny"}}, denied: true}, + {name: "within ceiling", effort: "low", ceiling: "medium", want: "low"}, + {name: "no policy", effort: "high", want: "high"}, + {name: "omitted", ceiling: "medium"}, + } { + t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", endpoint, platform, stream, tc.name), func(t *testing.T) { + cfg := &config.Config{} + groupID := int64(9400) + group := &service.Group{ + ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1, + MaxReasoningEffort: tc.ceiling, MaxReasoningEffortOverLimit: tc.overLimit, ReasoningEffortMappings: tc.mappings, + } + account := &service.Account{ + ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}}, + } + cache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}} + snapshot := service.NewSchedulerSnapshotService(cache, nil, nil, nil, nil) + upstream := &compatEffortPolicyUpstream{} + usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + billingRepo := &compatStreamUsageBillingRepo{} + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + gateway := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + h := &GatewayHandler{ + gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + + request := map[string]any{"model": model, "stream": stream} + if endpoint == "chat/completions" { + request["messages"] = []map[string]string{{"role": "user", "content": "hello"}} + if tc.effort != "" { + request["reasoning_effort"] = tc.effort + } + } else { + request["input"] = "hello" + if tc.effort != "" { + request["reasoning"] = map[string]string{"effort": tc.effort} + } + } + body, err := json.Marshal(request) + require.NoError(t, err) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + apiKey := &service.APIKey{ + ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, + User: &service.User{ID: 9403, Balance: 100}, + } + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403}) + if endpoint == "chat/completions" { + h.ChatCompletions(c) + } else { + h.Responses(c) + } + + if tc.denied { + require.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String()) + errorField := "error.type" + if endpoint == "responses" { + errorField = "error.code" + } + require.Equal(t, "permission_error", gjson.Get(recorder.Body.String(), errorField).String()) + require.Empty(t, upstream.bodies) + require.Zero(t, cache.snapshotCalls.Load(), "local policy denial precedes account selection") + require.Empty(t, usageRepo.created) + require.Empty(t, billingRepo.commands) + return + } + // Check the final Anthropic request, beyond handler parsing and both protocol conversions. + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Len(t, upstream.bodies, 1) + require.Equal(t, tc.want, gjson.GetBytes(upstream.bodies[0], "output_config.effort").String()) + require.Equal(t, model, gjson.GetBytes(upstream.bodies[0], "model").String()) + require.Contains(t, recorder.Body.String(), "partial") + require.Len(t, usageRepo.created, 1) + usage := <-usageRepo.created + if tc.effort == "" { + require.Nil(t, usage.RequestedReasoningEffort) + } else { + require.Equal(t, &tc.effort, usage.RequestedReasoningEffort) + require.Equal(t, &tc.want, usage.ReasoningEffort) + } + }) + } + } + } + } +} diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 1db2e0584a..3cfc580883 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -85,6 +85,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) { return } + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse) + return + } else if changed { + body = cappedBody + } reqStream, ok := parseOpenAICompatibleStream(body) if !ok { h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 79544a48de..da2ed97e29 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -85,6 +85,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) { return } + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + respondOpenAIReasoningEffortPolicyError(c, err, h.responsesErrorResponse) + return + } else if changed { + body = cappedBody + } reqStream, ok := parseOpenAICompatibleStream(body) if !ok { h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) From 177243016569651b7dc9141a58b13d97cd5b8a88 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 10:52:23 -0800 Subject: [PATCH 34/85] fix(accounts): keep Gemini usage visible during refetch --- frontend/src/components/account/AccountUsageCell.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index f6a7533838..8ccc433706 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -625,7 +625,7 @@ color="purple" /> -
+
From 6d7e6b9d842a9a791398cf1c5f41c19e2a09dba6 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 11:10:32 -0800 Subject: [PATCH 35/85] fix(gateway): record native Anthropic endpoints for error diagnostics --- .../openai_native_anthropic_endpoint_test.go | 143 ++++++++++++++++++ ...teway_chat_completions_anthropic_native.go | 1 + ...penai_gateway_messages_anthropic_native.go | 1 + ...enai_gateway_responses_anthropic_native.go | 1 + 4 files changed, 146 insertions(+) create mode 100644 backend/internal/handler/openai_native_anthropic_endpoint_test.go diff --git a/backend/internal/handler/openai_native_anthropic_endpoint_test.go b/backend/internal/handler/openai_native_anthropic_endpoint_test.go new file mode 100644 index 0000000000..f2a193c213 --- /dev/null +++ b/backend/internal/handler/openai_native_anthropic_endpoint_test.go @@ -0,0 +1,143 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/iotest" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type nativeEndpointUpstream struct { + service.HTTPUpstream + mode string + paths []string +} + +func (u *nativeEndpointUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + u.paths = append(u.paths, req.URL.Path) + if u.mode == "transport error" { + return nil, errors.New("synthetic upstream transport failure") + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}} + switch u.mode { + case "HTTP error": + response.StatusCode = http.StatusBadRequest + response.Body = io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"synthetic rejection"}}`)) + case "body read error": + response.Body = io.NopCloser(iotest.ErrReader(errors.New("synthetic body read failure"))) + default: + if gjson.GetBytes(body, "stream").Bool() { + response.Header.Set("Content-Type", "text/event-stream") + response.Body = io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)) + } else { + response.Body = io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"k3","content":[{"type":"text","text":"partial"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`)) + } + } + return response, nil +} + +func (u *nativeEndpointUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, accountID, concurrency) +} + +func TestOpenAINativeAnthropicEndpointDiagnostics(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, route := range []struct { + name string + path string + protocol string + platform string + }{ + {"messages", "/v1/messages", service.APIProtocolAnthropic, service.PlatformKimi}, + {"chat", "/v1/chat/completions", service.APIProtocolAnthropic, service.PlatformKimi}, + {"responses", "/v1/responses", service.APIProtocolAnthropic, service.PlatformKimi}, + {"adaptive messages", "/v1/messages", service.APIProtocolAdaptive, service.PlatformZhipu}, + } { + for _, stream := range []bool{false, true} { + for _, mode := range []string{"transport error", "HTTP error", "body read error", "success"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", route.name, stream, mode), func(t *testing.T) { + upstream := &nativeEndpointUpstream{mode: mode} + cfg := &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}} + gateway := service.NewOpenAIGatewayService( + nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, upstream, + nil, nil, nil, nil, nil, nil, nil, nil, + ) + account := &service.Account{ + ID: 9501, Platform: route.platform, Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", "api_protocol": route.protocol, + "base_url": "http://anthropic.example", + "api_base_urls": map[string]any{ + service.APIProtocolAnthropic: "http://anthropic.example", + service.APIProtocolChatCompletions: "http://chat.example", + }, + }, + } + model := "k3" + if route.protocol == service.APIProtocolAdaptive { + require.False(t, account.SupportsNativeCNResponses()) + model = "glm-5.3" + } + request := map[string]any{"model": model, "stream": stream} + if route.path == "/v1/responses" { + request["input"] = "hello" + } else { + request["messages"] = []map[string]string{{"role": "user", "content": "hello"}} + request["max_tokens"] = 32 + } + body, err := json.Marshal(request) + require.NoError(t, err) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, route.path, strings.NewReader(string(body))) + // The same Gin context can retain an earlier attempt's protocol. + service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions) + var result *service.OpenAIForwardResult + switch route.path { + case "/v1/messages": + result, err = gateway.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + case "/v1/chat/completions": + result, err = gateway.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + default: + result, err = gateway.Forward(context.Background(), c, account, body) + } + if mode == "success" { + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, EndpointMessages, result.UpstreamEndpoint) + require.Contains(t, recorder.Body.String(), "partial") + } else { + require.Error(t, err) + if mode != "body read error" { + require.Nil(t, result, "error diagnostics must work without a forward result") + } + } + require.Len(t, upstream.paths, 1) + require.True(t, strings.HasSuffix(upstream.paths[0], EndpointMessages), "the request actually used native Anthropic: %v", upstream.paths) + // This is the endpoint reader used when writing operations errors and result-less usage. + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, account.Platform)) + require.Equal(t, EndpointMessages, service.GetActualOpenAIUpstreamEndpoint(c)) + }) + } + } + } +} diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 5c2d86b87d..b630b78c34 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -42,6 +42,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( defaultMappedModel string, ) (*OpenAIForwardResult, error) { startTime := time.Now() + SetActualOpenAIUpstreamEndpoint(c, "/v1/messages") // 1. Parse Chat Completions request var ccReq apicompat.ChatCompletionsRequest diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 3156aa8546..82e3c89871 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -40,6 +40,7 @@ func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint( defaultMappedModel string, ) (*OpenAIForwardResult, error) { startTime := time.Now() + SetActualOpenAIUpstreamEndpoint(c, "/v1/messages") originalModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) if originalModel == "" { diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index d4ed554a71..3f36d0d30b 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -42,6 +42,7 @@ func (s *OpenAIGatewayService) forwardResponsesViaNativeAnthropic( defaultMappedModel string, ) (*OpenAIForwardResult, error) { startTime := time.Now() + SetActualOpenAIUpstreamEndpoint(c, "/v1/messages") // 1. Lower Codex client-side tools to function tools understood by Anthropic. adaptedBody, clientToolMapping, err := adaptResponsesClientToolsForAnthropic(body) From bd89d3d943c0b2dafaf927f6665ea90ccfaaada8 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 15:32:49 -0800 Subject: [PATCH 36/85] fix(gateway): preserve message output config with per-turn beta --- backend/internal/pkg/claude/constants.go | 1 + ...way_mid_conversation_output_config_test.go | 126 +++++++++++++++++- backend/internal/service/gateway_request.go | 14 +- 3 files changed, 128 insertions(+), 13 deletions(-) diff --git a/backend/internal/pkg/claude/constants.go b/backend/internal/pkg/claude/constants.go index 17c864328d..6f4135d0da 100644 --- a/backend/internal/pkg/claude/constants.go +++ b/backend/internal/pkg/claude/constants.go @@ -31,6 +31,7 @@ const ( BetaContextManagement = "context-management-2025-06-27" BetaThinkingBindingControls = "thinking-binding-controls-2026-08-01" BetaMidConversationOutputConfig = "mid-conversation-output-config-2026-07-01" + BetaPerTurnControl = "per-turn-control-2026-07-01" BetaExtendedCacheTTL = "extended-cache-ttl-2025-04-11" // server-side refusal fallback beta 字段族(beta Messages API 专有)。 diff --git a/backend/internal/service/gateway_mid_conversation_output_config_test.go b/backend/internal/service/gateway_mid_conversation_output_config_test.go index d551fae785..2c563c1778 100644 --- a/backend/internal/service/gateway_mid_conversation_output_config_test.go +++ b/backend/internal/service/gateway_mid_conversation_output_config_test.go @@ -5,8 +5,10 @@ package service import ( "bytes" "context" + "io" "net/http" "net/http/httptest" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/config" @@ -17,7 +19,7 @@ import ( ) // ============================================================================ -// message-level output_config ↔ mid-conversation-output-config beta +// message-level output_config ↔ mid-conversation-output-config / per-turn-control beta // ============================================================================ // // 背景:pi-ai(Harness 使用的 Anthropic provider)会为 opus5 生成形如 @@ -32,11 +34,11 @@ import ( // "output_config: Extra inputs are not permitted" // // 修复策略(剥字段,不注入 beta): -// - header 缺该 token:仅为携带 message-level output_config 的消息剥此字段; +// - header 缺这两种 token:仅为携带 message-level output_config 的消息剥此字段; // role=system 且 content 无正文(缺失 / null / 空 string / 空 array / 仅空 // text 块)时整条删除;system 有正文保留正文与其余字段;user/assistant 只剥 // 字段,绝不整条删除。 -// - header 含该 token:完全保留。 +// - header 含任一 token:完全保留。 // - 无任何 message-level output_config:字节 no-op。 // - 顶层 output_config / effort 不受该 beta 约束,本增量不触碰。 // @@ -154,10 +156,120 @@ func TestSanitizeAnthropicBodyForBetaTokens_MidConversationOutputConfig_SystemWi // header 含该 beta → 完全保留,字节 no-op(即使是空控制 system 消息)。 func TestSanitizeAnthropicBodyForBetaTokens_MidConversationOutputConfig_ByteNoopWhenBetaPresent(t *testing.T) { body := []byte(`{"model":"claude-opus-5","output_config":{"effort":"high"},"messages":[{"role":"system","content":[],"output_config":{"effort":"high"}},{"role":"user","content":"hi"}]}`) - out, changed := sanitizeAnthropicBodyForBetaTokens(body, - "claude-code-20250219,oauth-2025-04-20,"+claude.BetaMidConversationOutputConfig) - require.False(t, changed, "header 含 mid-conversation-output-config beta → 完全保留") - require.True(t, bytes.Equal(body, out), "含 beta 时必须字节 no-op") + for _, beta := range []string{ + claude.BetaMidConversationOutputConfig, + "per-turn-control-2026-07-01", + "per-turn-control-2026-07-01," + claude.BetaMidConversationOutputConfig, + } { + t.Run(beta, func(t *testing.T) { + out, changed := sanitizeAnthropicBodyForBetaTokens(body, "claude-code-20250219, "+beta+" ") + require.False(t, changed, "a supported beta must preserve message-level output_config") + require.True(t, bytes.Equal(body, out), "含 beta 时必须字节 no-op") + }) + } +} + +func TestForward_PerTurnControlMessageOutputConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + const perTurnBeta = "per-turn-control-2026-07-01" + const body = `{"model":"claude-opus-5","max_tokens":256,"output_config":{"effort":"high"},` + + `"metadata":{"user_id":"user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account_550e8400-e29b-41d4-a716-446655440000_session_123e4567-e89b-12d3-a456-426614174000"},` + + `"messages":[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"},` + + `{"role":"system","content":[],"output_config":{"effort":"low"}},` + + `{"role":"user","content":"Summarize that in one sentence."}]}` + for _, mode := range []string{"oauth_claude_code", "oauth_mimic", "apikey", "apikey_passthrough"} { + for _, withBeta := range []bool{true, false} { + name := "without_beta" + if withBeta { + name = "with_beta" + } + t.Run(mode+"/"+name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + c.Request.Header.Set("User-Agent", "claude-cli/2.1.321") + if mode == "oauth_mimic" { + c.Request.Header.Set("User-Agent", "third-party-client/1.0") + } + if withBeta { + c.Request.Header.Set("Anthropic-Beta", "claude-code-20250219,"+perTurnBeta) + } + account := newAnthropicAPIKeyAccountForTest() + account.Extra["anthropic_passthrough"] = mode == "apikey_passthrough" + if strings.HasPrefix(mode, "oauth") { + account = newAnthropicOAuthAccountForPartialUsageTest() + } + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"msg_test","type":"message","role":"assistant",` + + `"model":"claude-opus-5","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn",` + + `"usage":{"input_tokens":10,"output_tokens":1}}`)), + }} + parsed, err := ParseGatewayRequest(NewRequestBodyRef([]byte(body)), PlatformAnthropic) + require.NoError(t, err) + svc := newForwardPartialUsageServiceForTest(upstream) + _, err = svc.Forward(context.Background(), c, account, parsed) + require.NoError(t, err) + require.NotNil(t, upstream.lastReq) + + beta := getHeaderRaw(upstream.lastReq.Header, "anthropic-beta") + require.Equal(t, withBeta && mode != "oauth_mimic", anthropicBetaTokensContains(beta, perTurnBeta)) + wantControl := withBeta || mode == "oauth_mimic" + messages := gjson.GetBytes(upstream.lastBody, "messages").Array() + if wantControl { + require.Len(t, messages, 4) + require.Equal(t, "system", messages[2].Get("role").String()) + require.Equal(t, "[]", messages[2].Get("content").Raw) + require.Equal(t, "low", messages[2].Get("output_config.effort").String()) + } else { + require.Len(t, messages, 3) + } + require.Equal(t, "Hello", messages[0].Get("content").String()) + require.Equal(t, "Hi", messages[1].Get("content").String()) + require.Equal(t, "Summarize that in one sentence.", messages[len(messages)-1].Get("content").String()) + require.Equal(t, "high", gjson.GetBytes(upstream.lastBody, "output_config.effort").String()) + }) + } + } +} + +func TestBuildUpstreamRequest_PerTurnControlPolicyFilter(t *testing.T) { + gin.SetMode(gin.TestMode) + const perTurnBeta = "per-turn-control-2026-07-01" + const midConversationBeta = "mid-conversation-output-config-2026-07-01" + body := []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"Hello"},` + + `{"role":"system","content":[],"output_config":{"effort":"low"}}]}`) + for _, tc := range []struct { + name string + drop []string + keep bool + }{ + {"drop_per_turn_only", []string{perTurnBeta}, true}, + {"drop_mid_conversation_only", []string{midConversationBeta}, true}, + {"drop_both", []string{perTurnBeta, midConversationBeta}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Request.Header.Set("Anthropic-Beta", "claude-code-20250219,"+perTurnBeta+","+midConversationBeta) + c.Set(betaPolicyFilterSetKey, buildBetaTokenSet(tc.drop)) + svc := &GatewayService{cfg: &config.Config{}} + req, _, err := svc.buildUpstreamRequest(context.Background(), c, + newAnthropicOAuthAccountForPartialUsageTest(), body, + "oauth-token", "oauth", "claude-opus-5", false, false) + require.NoError(t, err) + for _, token := range tc.drop { + require.False(t, anthropicBetaTokensContains(getHeaderRaw(req.Header, "anthropic-beta"), token)) + } + out := readUpstreamBodyForTest(t, req) + require.Equal(t, tc.keep, gjson.GetBytes(out, "messages.1.output_config").Exists()) + if tc.keep { + require.Equal(t, "low", gjson.GetBytes(out, "messages.1.output_config.effort").String()) + } else { + require.Len(t, gjson.GetBytes(out, "messages").Array(), 1) + } + }) + } } // 无 message-level output_config(仅有顶层 output_config,或完全没有)→ 字节 no-op。 diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index 95dfb069a3..2abbe5e1a8 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -1085,8 +1085,9 @@ const anthropicBetaContextManagementToken = "context-management-2025-06-27" // - pi-ai(Harness 使用的 Anthropic provider)会为 opus5 生成形如 // `{"role":"system","content":[],"output_config":{"effort":"high"}}` 的控制消息, // 并请求 `mid-conversation-output-config-2026-07-01` beta -// - 该 output_config 是 **message 级**字段,只有该 beta 保护;顶层 output_config/effort -// 不受它约束 +// - Claude Code 也会以 `per-turn-control-2026-07-01` 请求该能力 +// - 该 output_config 是 **message 级**字段,由上述任一 beta 保护;顶层 output_config/effort +// 不受它们约束 // - OAuth mimic 用 FullClaudeCodeMimicryBetas 覆盖客户端 beta;固定列表漏该 beta 时 // body 字段与 header 不对称 → 上游报 "output_config: Extra inputs are not permitted" // - 缺 token 时净化消息级 output_config(详见 stripAnthropicMessageOutputConfigUnlessBeta) @@ -1137,7 +1138,7 @@ func sanitizeAnthropicBodyForBetaTokens(body []byte, anthropicBetaHeader string) body, changed = b, true } - // messages[].output_config:mid-conversation-output-config beta 专属字段。 + // messages[].output_config:需要 mid-conversation-output-config 或 per-turn-control beta。 // 顶层 output_config / effort 不受该 beta 约束,本分支只净化消息内字段。 if b, deleted := stripAnthropicMessageOutputConfigUnlessBeta(body, anthropicBetaHeader); deleted { body, changed = b, true @@ -1186,17 +1187,18 @@ func anthropicBetaTokensContains(header, token string) bool { } // stripAnthropicMessageOutputConfigUnlessBeta 在 anthropic-beta header 缺 -// mid-conversation-output-config beta 时,净化 **messages[].output_config**: +// mid-conversation-output-config 和 per-turn-control 两种 beta 时,净化 **messages[].output_config**: // - 仅为携带 message-level output_config 的消息剥该字段; // - 若该消息 role=system 且 content 无正文(缺失 / null / 空 string / 空 array / // 仅空 text 块),整条删除(pi-ai 为 opus5 生成的空 system 控制消息即此形态); // - system 有正文则保留正文与其余字段;user/assistant 只剥字段,绝不整条删除; // - 无任何消息携带该字段时返回原 body(字节 no-op)。 // -// header 含该 beta 时完全保留。顶层 output_config / effort 不属于该 beta 保护范围, +// header 含任一 beta 时完全保留。顶层 output_config / effort 不属于这些 beta 保护范围, // 本函数不做任何处理。多条删除用「稳健重建」实现,保留其余字段与消息先后顺序。 func stripAnthropicMessageOutputConfigUnlessBeta(body []byte, anthropicBetaHeader string) ([]byte, bool) { - if anthropicBetaTokensContains(anthropicBetaHeader, claude.BetaMidConversationOutputConfig) { + if anthropicBetaTokensContains(anthropicBetaHeader, claude.BetaMidConversationOutputConfig) || + anthropicBetaTokensContains(anthropicBetaHeader, claude.BetaPerTurnControl) { return body, false } // 快速路径:body 中不含 output_config 字面量时无需解析。 From fc8af440ed517602b682dc9d2c1630eadf6f4392 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Thu, 12 Nov 2026 16:21:43 -0800 Subject: [PATCH 37/85] test(billing): fix peak-rate usage test clock --- backend/internal/service/gateway_record_usage_test.go | 2 ++ backend/internal/service/openai_gateway_record_usage_test.go | 2 ++ 2 files changed, 4 insertions(+) diff --git a/backend/internal/service/gateway_record_usage_test.go b/backend/internal/service/gateway_record_usage_test.go index 9dfa556298..d97aad6af8 100644 --- a/backend/internal/service/gateway_record_usage_test.go +++ b/backend/internal/service/gateway_record_usage_test.go @@ -362,6 +362,8 @@ func TestGatewayServiceRecordUsage_PeakRateAffectsTokenModeImageOutputTokens(t * }, User: &User{ID: 602}, Account: &Account{ID: 702}, + // The peak window excludes 23:59, so do not depend on the wall clock. + PricingAt: time.Date(2026, time.January, 15, 12, 0, 0, 0, time.UTC), }) require.NoError(t, err) diff --git a/backend/internal/service/openai_gateway_record_usage_test.go b/backend/internal/service/openai_gateway_record_usage_test.go index be4cf1850c..b1e2bde2f4 100644 --- a/backend/internal/service/openai_gateway_record_usage_test.go +++ b/backend/internal/service/openai_gateway_record_usage_test.go @@ -476,6 +476,8 @@ func TestOpenAIGatewayServiceRecordUsage_PeakRateAffectsTokenModeImageOutputToke }, User: &User{ID: 2004}, Account: &Account{ID: 3004}, + // The peak window excludes 23:59, so do not depend on the wall clock. + PricingAt: time.Date(2026, time.January, 15, 12, 0, 0, 0, time.UTC), }) require.NoError(t, err) From b9d02c31a5ba47d21262ad50a37599456033e861 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:30:13 -0800 Subject: [PATCH 38/85] fix(gateway): observe Anthropic chat completion models --- .../gateway_forward_as_chat_completions.go | 51 ++++++++++++------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index a1f9786719..fe2fc6c561 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -236,6 +236,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( reasoningEffort *string, startTime time.Time, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") scanner := bufio.NewScanner(resp.Body) @@ -271,6 +272,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( continue } + observer.ObserveAnthropic([]byte(payload)) streamStatus.observe(&event, payload) if streamStatus.upstreamErrType != "" { break @@ -323,7 +325,10 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( _ = resp.Body.Close() writeGatewayCCError(c, http.StatusBadGateway, "server_error", failure.message) return &ForwardResult{ - RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), }, failure.err @@ -367,14 +372,17 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( } return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: false, - Duration: time.Since(startTime), + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -388,6 +396,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( reasoningEffort *string, startTime time.Time, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") if s.responseHeaderFilter != nil { @@ -415,16 +424,19 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( resultWithUsage := func() *ForwardResult { return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - ClientDisconnect: stream.clientDisconnected, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: stream.clientDisconnected, } } @@ -522,6 +534,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( // The intermediate Responses converter synthesizes usage even when absent. ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) + observer.ObserveAnthropic([]byte(payload)) stream.observe(&event, payload) if stream.upstreamErrType != "" { break From de34f50c1a2a723ae8717f56c964f1ebef3fc6ea Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:31:51 -0800 Subject: [PATCH 39/85] fix(gateway): observe Anthropic Responses models --- .../service/gateway_forward_as_responses.go | 51 ++++++++++++------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index db10be2568..8cc345869a 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -385,6 +385,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( startTime time.Time, clientToolMapping apicompat.ResponsesClientToolMapping, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") scanner := bufio.NewScanner(resp.Body) @@ -427,6 +428,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( continue } + observer.ObserveAnthropic([]byte(payload)) streamStatus.observe(&event, payload) if streamStatus.upstreamErrType != "" { break @@ -483,7 +485,10 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( _ = resp.Body.Close() writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message) return &ForwardResult{ - RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), }, failure.err @@ -532,14 +537,17 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( } return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: false, - Duration: time.Since(startTime), + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -554,6 +562,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( startTime time.Time, clientToolMapping apicompat.ResponsesClientToolMapping, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") if s.responseHeaderFilter != nil { @@ -579,16 +588,19 @@ func (s *GatewayService) handleResponsesStreamingResponse( resultWithUsage := func() *ForwardResult { return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - ClientDisconnect: stream.clientDisconnected, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: stream.clientDisconnected, } } @@ -705,6 +717,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( continue } + observer.ObserveAnthropic([]byte(payload)) stream.observe(&event, payload) if stream.upstreamErrType != "" { break From c487b215faea7a4158c20e74c5796d51c4393471 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:33:35 -0800 Subject: [PATCH 40/85] test(gateway): cover Anthropic compatibility observations --- .../service/gateway_anthropic_compat_observation_test.go | 1 + 1 file changed, 1 insertion(+) create mode 100644 backend/internal/service/gateway_anthropic_compat_observation_test.go diff --git a/backend/internal/service/gateway_anthropic_compat_observation_test.go b/backend/internal/service/gateway_anthropic_compat_observation_test.go new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/backend/internal/service/gateway_anthropic_compat_observation_test.go @@ -0,0 +1 @@ + From 90f115132490b39be090459455cdb51fdda43df9 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:35:33 -0800 Subject: [PATCH 41/85] test(gateway): add observation regression cases --- ...teway_anthropic_compat_observation_test.go | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/backend/internal/service/gateway_anthropic_compat_observation_test.go b/backend/internal/service/gateway_anthropic_compat_observation_test.go index 8b13789179..115c77d665 100644 --- a/backend/internal/service/gateway_anthropic_compat_observation_test.go +++ b/backend/internal/service/gateway_anthropic_compat_observation_test.go @@ -1 +1,73 @@ +//go:build unit +package service + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAnthropicCompatUpstreamObservation(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, protocol := range []string{"chat", "responses"} { + for _, streaming := range []bool{false, true} { + for _, scenario := range []string{"normal", "missing", "conflict", "partial-error"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", protocol, streaming, scenario), func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + beginUpstreamResponseModelObservation(c).Observe("stale-model", false) + body := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"actual-model\",\"usage\":{\"input_tokens\":3,\"speed\":\"fast\"}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + + expectedModel, expectedTier := "actual-model", "fast" + switch scenario { + case "missing": + body = strings.ReplaceAll(body, `,"model":"actual-model"`, "") + body = strings.ReplaceAll(body, `,"speed":"fast"`, "") + expectedModel, expectedTier = "", "" + case "conflict": + body = strings.Replace(body, `"type":"message_delta","delta"`, `"type":"message_delta","model":"other-model","delta"`, 1) + case "partial-error": + body = body[:strings.Index(body, "event: message_delta")] + } + resp := &http.Response{Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)} + svc := &GatewayService{} + var result *ForwardResult + var err error + if protocol == "chat" { + if streaming { + result, err = svc.handleCCStreamingFromAnthropic(resp, c, "public-model", "sent-model", nil, time.Now()) + } else { + result, err = svc.handleCCBufferedFromAnthropic(resp, c, "public-model", "sent-model", nil, time.Now()) + } + } else { + if streaming { + result, err = svc.handleResponsesStreamingResponse(resp, c, "public-model", "sent-model", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + } else { + result, err = svc.handleResponsesBufferedStreamingResponse(resp, c, "public-model", "sent-model", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + } + } + if scenario == "partial-error" { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, expectedModel, result.UpstreamResponseModel) + require.Equal(t, expectedTier, result.UpstreamResponseServiceTier) + require.Equal(t, scenario == "conflict", result.UpstreamResponseModelConflict) + require.Equal(t, "sent-model", result.UpstreamModel) + require.Equal(t, "public-model", result.Model) + }) + } + } + } +} From 734b922bd8e71b33ff34901c1601d49afa8dbc3d Mon Sep 17 00:00:00 2001 From: Anand Biju <169837340+Anandb71@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:12 +0530 Subject: [PATCH 42/85] fix(claude): default account tests to claude-sonnet-4-6 claude-sonnet-4-5-20250929 is deprecated and retires on the Claude API on November 30, 2026: https://platform.claude.com/docs/en/about-claude/model-deprecations claude.DefaultTestModel is what an account connection test sends when no model is picked, so after that date the default test would fail even for healthy accounts. Move it to claude-sonnet-4-6, which the gateway already uses for the Antigravity test default and maps for Bedrock. Signed-off-by: Anand Biju <169837340+Anandb71@users.noreply.github.com> --- backend/internal/pkg/claude/constants.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/pkg/claude/constants.go b/backend/internal/pkg/claude/constants.go index 17c864328d..e52cab8406 100644 --- a/backend/internal/pkg/claude/constants.go +++ b/backend/internal/pkg/claude/constants.go @@ -253,7 +253,7 @@ func DefaultModelIDs() []string { } // DefaultTestModel 测试时使用的默认模型 -const DefaultTestModel = "claude-sonnet-4-5-20250929" +const DefaultTestModel = "claude-sonnet-4-6" // ModelIDOverrides Claude OAuth 请求需要的模型 ID 映射 var ModelIDOverrides = map[string]string{ From fd648775810ed4348a44daaacaf38042d4927486 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Fri, 13 Nov 2026 16:03:16 +0800 Subject: [PATCH 43/85] fix(codex): preserve additional_tools declaration IDs --- .../openai_codex_additional_tools_test.go | 113 ++++++++++++++++++ .../service/openai_codex_transform.go | 5 +- 2 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/openai_codex_additional_tools_test.go diff --git a/backend/internal/service/openai_codex_additional_tools_test.go b/backend/internal/service/openai_codex_additional_tools_test.go new file mode 100644 index 0000000000..c6c2e1bacf --- /dev/null +++ b/backend/internal/service/openai_codex_additional_tools_test.go @@ -0,0 +1,113 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestFilterCodexInput_AdditionalToolsDeclarationID(t *testing.T) { + for _, preserveReferences := range []bool{false, true} { + t.Run(fmt.Sprintf("references=%t", preserveReferences), func(t *testing.T) { + input := []any{ + map[string]any{ + "type": "additional_tools", "id": "at_discovery", "role": "developer", + "tools": []any{map[string]any{"type": "tool_search", "execution": "client"}}, + }, + map[string]any{"type": "message", "id": "msg_history", "role": "user", "content": "find a tool"}, + map[string]any{"type": "reasoning", "id": "rs_history", "encrypted_content": "sealed", "summary": []any{}}, + map[string]any{"type": "item_reference", "id": "msg_reference"}, + } + original, err := json.Marshal(input) + require.NoError(t, err) + + filtered := filterCodexInput(input, preserveReferences) + encoded, err := json.Marshal(filtered) + require.NoError(t, err) + require.Equal(t, "at_discovery", gjson.GetBytes(encoded, "0.id").String()) + require.Equal(t, "tool_search", gjson.GetBytes(encoded, "0.tools.0.type").String()) + require.Equal(t, preserveReferences, gjson.GetBytes(encoded, "1.id").Exists()) + require.False(t, gjson.GetBytes(encoded, "2.id").Exists()) + require.Equal(t, "sealed", gjson.GetBytes(encoded, "2.encrypted_content").String()) + require.Equal(t, preserveReferences, gjson.GetBytes(encoded, "3.id").Exists()) + after, err := json.Marshal(input) + require.NoError(t, err) + require.JSONEq(t, string(original), string(after), "filtering must not mutate the caller's input") + }) + } +} + +func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, passthrough := range []bool{false, true} { + for _, lite := range []bool{false, true} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("passthrough=%t/lite=%t/stream=%t", passthrough, lite, stream), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{ + "model":"gpt-6.1-sol","stream":%t,"store":false,"instructions":"test instructions", + "input":[ + {"type":"additional_tools","id":"at_discovery","role":"developer","tools":[ + {"type":"tool_search","execution":"client"}, + {"type":"namespace","name":"multi_agent_v1","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"},"defer_loading":true}]} + ]}, + {"type":"message","id":"msg_history","role":"user","content":[{"type":"input_text","text":"find spawn_agent"}]}, + {"type":"reasoning","id":"rs_history","encrypted_content":"sealed","summary":[]} + ] + }`, stream)) + upstreamSSE := strings.Join([]string{ + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"tool_search_call","id":"tsc_discovery","call_id":"tsc_discovery","execution":"client","arguments":"{\"query\":\"spawn_agent\"}"}}`, + "", + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"tool_search_call","id":"tsc_discovery","call_id":"tsc_discovery","execution":"client","arguments":"{\"query\":\"spawn_agent\"}"}}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_discovery","status":"completed","model":"gpt-6.1-sol","output":[{"type":"tool_search_call","id":"tsc_discovery","call_id":"tsc_discovery","execution":"client","arguments":"{\"query\":\"spawn_agent\"}"}],"usage":{"input_tokens":2,"output_tokens":1,"total_tokens":3}}}`, + "", "data: [DONE]", "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 8752, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token", "chatgpt_account_id": "test-account"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + Status: StatusActive, Schedulable: true, + } + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.167.0") + if lite { + c.Request.Header.Set(responsesLiteHeader, "true") + } + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", upstream.lastReq.URL.String()) + require.Equal(t, "at_discovery", gjson.GetBytes(upstream.lastBody, "input.0.id").String()) + require.JSONEq(t, gjson.GetBytes(body, "input.0").Raw, gjson.GetBytes(upstream.lastBody, "input.0").Raw) + require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.1.id").Exists()) + require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.2.id").Exists()) + require.Equal(t, "sealed", gjson.GetBytes(upstream.lastBody, "input.2.encrypted_content").String()) + require.Contains(t, recorder.Body.String(), `"type":"tool_search_call"`) + require.Contains(t, recorder.Body.String(), `"call_id":"tsc_discovery"`) + require.NotContains(t, recorder.Body.String(), `"type":"function_call"`) + }) + } + } + } +} diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index f4b33dbab3..bbc60f7555 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -1743,7 +1743,10 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an } } - if !opts.PreserveReferences { + // additional_tools IDs identify declarations carried in this request, + // not stored history. Removing them can change native tool discovery + // into ordinary function calls even with store=false. + if !opts.PreserveReferences && typ != "additional_tools" { ensureCopy() delete(newItem, "id") } else if id, ok := m["id"].(string); ok && shouldStripOpenAIResponsesInputItemID(typ, id) { From 8480cb0cd95710de66052dabf364f6e62d267f0f Mon Sep 17 00:00:00 2001 From: r266-tech Date: Fri, 13 Nov 2026 18:06:45 +0800 Subject: [PATCH 44/85] fix(antigravity): match schema items to the selected type --- .../pkg/antigravity/schema_cleaner.go | 17 ++--- .../antigravity_gateway_compat_test.go | 68 +++++++++++++++++++ 2 files changed, 72 insertions(+), 13 deletions(-) diff --git a/backend/internal/pkg/antigravity/schema_cleaner.go b/backend/internal/pkg/antigravity/schema_cleaner.go index 73cf362561..75b5fa1e1d 100644 --- a/backend/internal/pkg/antigravity/schema_cleaner.go +++ b/backend/internal/pkg/antigravity/schema_cleaner.go @@ -376,24 +376,15 @@ func cleanJSONSchemaRecursive(value any) any { } } - // 8. [SAFETY] 处理缺失 items 的 Array (Gemini 严苛要求 array 必须声明 items Schema) + // 8. Gemini 只允许 array 携带 items,且 items 必须是非空 Schema 对象。 if t, _ := schemaMap["type"].(string); t == "array" { - itemsVal, hasItems := schemaMap["items"] - needDefaultItems := false - if !hasItems || itemsVal == nil { - needDefaultItems = true - } else if itemsMap, ok := itemsVal.(map[string]any); ok { - if len(itemsMap) == 0 { - needDefaultItems = true - } - } else if _, isBool := itemsVal.(bool); isBool { - needDefaultItems = true - } - if needDefaultItems { + if items, ok := schemaMap["items"].(map[string]any); !ok || len(items) == 0 { schemaMap["items"] = map[string]any{ "type": "string", } } + } else { + delete(schemaMap, "items") } // 9. [SAFETY] Required 字段对齐 diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index bccbe2472f..1e1178e9b8 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -132,6 +132,74 @@ func antigravityCompatSuccessResponse() *http.Response { } } +func TestAntigravityCompatToolSchemaItemsMatchSelectedType(t *testing.T) { + gin.SetMode(gin.TestMode) + const schema = `{"type":"object","properties":{ + "uri":{"type":["string","array"],"items":{"type":"string"}}, + "paths":{"type":["array","string"],"items":{"type":"integer"}}, + "nested":{"type":"array","items":{"type":"object","properties":{ + "uri":{"type":["string","array"],"items":{"type":"string"}} + }}}, + "fallback":{"type":"array","items":17}, + "inferred":{"items":{"type":"integer"}}, + "items":{"type":"string"} + }}` + const expected = `{"type":"object","properties":{ + "uri":{"type":"string"}, + "paths":{"type":"array","items":{"type":"integer"}}, + "nested":{"type":"array","items":{"type":"object","properties":{ + "uri":{"type":"string"} + }}}, + "fallback":{"type":"array","items":{"type":"string"}}, + "inferred":{"type":"array","items":{"type":"integer"}}, + "items":{"type":"string"} + }}` + for _, protocol := range []string{"chat", "responses", "messages"} { + t.Run(protocol, func(t *testing.T) { + var parameters map[string]any + require.NoError(t, json.Unmarshal([]byte(schema), ¶meters)) + tool := map[string]any{"name": "inspect", "parameters": parameters} + request := map[string]any{"model": "gemini-3.1-pro-high", "max_tokens": 128} + switch protocol { + case "chat": + request["messages"] = []map[string]any{{"role": "user", "content": "inspect URI"}} + request["tools"] = []any{map[string]any{"type": "function", "function": tool}} + case "responses": + request["input"] = "inspect URI" + tool["type"] = "function" + request["tools"] = []any{tool} + case "messages": + request["messages"] = []map[string]any{{"role": "user", "content": "inspect URI"}} + request["tools"] = []any{map[string]any{"name": "inspect", "input_schema": parameters}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + var forwarded []byte + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{antigravityCompatSuccessResponse()}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + forwarded, err = io.ReadAll(req.Body) + require.NoError(t, err) + }, + } + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/"+protocol, body) + switch protocol { + case "chat": + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + case "responses": + _, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + case "messages": + _, err = svc.Forward(context.Background(), c, account, body, false) + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.JSONEq(t, expected, gjson.GetBytes(forwarded, "request.tools.0.functionDeclarations.0.parameters").Raw) + }) + } +} + func TestAntigravitySystemIdentityAcrossProtocols(t *testing.T) { gin.SetMode(gin.TestMode) const task = "\nKeep GPT-5.6, gpt-6 and Claude model ids unchanged." From 8dcdfff22a7ad9568a1c2f88900809dd8eeb4f56 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Fri, 13 Nov 2026 20:16:55 +0800 Subject: [PATCH 45/85] fix(codex): normalize UUID additional tool declaration IDs --- .../openai_codex_additional_tools_test.go | 110 +++++++++++++++++- .../service/openai_codex_transform.go | 91 ++++++++++++++- .../service/openai_gateway_request_body.go | 6 + 3 files changed, 203 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/openai_codex_additional_tools_test.go b/backend/internal/service/openai_codex_additional_tools_test.go index c6c2e1bacf..d11fe49480 100644 --- a/backend/internal/service/openai_codex_additional_tools_test.go +++ b/backend/internal/service/openai_codex_additional_tools_test.go @@ -48,6 +48,108 @@ func TestFilterCodexInput_AdditionalToolsDeclarationID(t *testing.T) { } } +func TestFilterCodexInput_AdditionalToolsUUID(t *testing.T) { + const uuidID = "at_00112233-4455-4677-8899-aabbccddeeff" + const compactID = "at_00112233445546778899aabbccddeeff" + for _, tc := range []struct { + name string + id any + want any + }{ + {"hyphenated", uuidID, compactID}, + {"uppercase", "at_00112233-4455-4677-8899-AABBCCDDEEFF", "at_00112233445546778899AABBCCDDEEFF"}, + {"compact", compactID, compactID}, + {"opaque", "at_discovery", "at_discovery"}, + {"wrong_prefix", "xx_00112233-4455-4677-8899-aabbccddeeff", "xx_00112233-4455-4677-8899-aabbccddeeff"}, + {"non_hex", "at_z0112233-4455-4677-8899-aabbccddeeff", "at_z0112233-4455-4677-8899-aabbccddeeff"}, + {"misplaced_hyphen", "at_0011223-34455-4677-8899-aabbccddeeff", "at_0011223-34455-4677-8899-aabbccddeeff"}, + {"extra_hyphens", "at_0011223--4455-4677-8899-aabbccddeef-", "at_0011223--4455-4677-8899-aabbccddeef-"}, + {"short", "at_00112233-4455-4677-8899-aabbccddee", "at_00112233-4455-4677-8899-aabbccddee"}, + {"whitespace", " " + uuidID, " " + uuidID}, + {"numeric", 42, 42}, + {"null", nil, nil}, + } { + for _, preserveReferences := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/references=%t", tc.name, preserveReferences), func(t *testing.T) { + declaration := map[string]any{ + "type": "additional_tools", "id": tc.id, "role": "developer", + "tools": []any{map[string]any{"type": "tool_search", "execution": "client"}}, + } + reference := map[string]any{"type": "item_reference", "id": tc.id} + input := []any{declaration, reference} + filtered := filterCodexInput(input, preserveReferences) + want := map[string]any{ + "type": "additional_tools", "id": tc.want, "role": "developer", "tools": declaration["tools"], + } + require.Equal(t, want, filtered[0]) + if preserveReferences { + require.Equal(t, map[string]any{"type": "item_reference", "id": tc.want}, filtered[1]) + } else { + require.Len(t, filtered, 1) + } + require.Equal(t, tc.id, declaration["id"], "normalization must not mutate the declaration") + require.Equal(t, tc.id, reference["id"], "normalization must not mutate references") + require.Equal(t, filtered, filterCodexInput(filtered, preserveReferences), "normalization must be idempotent") + }) + } + } + + t.Run("only_declared_tools", func(t *testing.T) { + input := []any{ + map[string]any{"type": "additional_tools", "tools": []any{}}, + map[string]any{"type": "message", "id": "msg_00112233-4455-4677-8899-aabbccddeeff", "role": "user", "content": "hello"}, + map[string]any{"type": "item_reference", "id": uuidID}, + map[string]any{"type": "item_reference", "id": "at_11112233-4455-4677-8899-aabbccddeeff"}, + } + require.Equal(t, input, filterCodexInput(input, true), "do not invent IDs or rewrite unrelated history/references") + }) +} + +func TestOpenAIResponsesCompatibility_AdditionalToolsUUID(t *testing.T) { + const uuidID = "at_00112233-4455-4677-8899-aabbccddeeff" + const compactID = "at_00112233445546778899aabbccddeeff" + for _, accountType := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + t.Run(accountType, func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","marker":"\u0061","number":9007199254740993,"input":[` + + `{"type":"item_reference","id":"` + uuidID + `"},` + + `{"type":"additional_tools","id":"` + uuidID + `","role":"developer","tools":[{"type":"tool_search","execution":"client"}]},` + + `{"type":"future_item","id":"` + uuidID + `"},` + + `{"type":"additional_tools","id":"at_discovery","tools":[]},` + + `{"type":"additional_tools","id":"at_z0112233-4455-4677-8899-aabbccddeeff","tools":[]},` + + `{"type":"message","id":"msg_test","role":"user","content":"` + uuidID + `"}]}`) + original := bytes.Clone(body) + account := &Account{Platform: PlatformOpenAI, Type: accountType} + normalized, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.Equal(t, accountType == AccountTypeOAuth, changed) + wantID := uuidID + if accountType == AccountTypeOAuth { + wantID = compactID + } + require.Equal(t, wantID, gjson.GetBytes(normalized, "input.0.id").String(), "references can precede declarations") + require.Equal(t, wantID, gjson.GetBytes(normalized, "input.1.id").String()) + for _, index := range []int{2, 3, 4, 5} { + path := fmt.Sprintf("input.%d", index) + require.Equal(t, gjson.GetBytes(body, path).Raw, gjson.GetBytes(normalized, path).Raw) + } + require.Equal(t, `"\u0061"`, gjson.GetBytes(normalized, "marker").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(normalized, "number").Raw) + require.Equal(t, original, body) + again, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(normalized, account, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, normalized, again) + }) + } + t.Run("undeclared_reference", func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","input":[{"type":"item_reference","id":"` + uuidID + `"}]}`) + normalized, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, body, normalized) + }) +} + func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { gin.SetMode(gin.TestMode) for _, passthrough := range []bool{false, true} { @@ -57,7 +159,7 @@ func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { body := []byte(fmt.Sprintf(`{ "model":"gpt-6.1-sol","stream":%t,"store":false,"instructions":"test instructions", "input":[ - {"type":"additional_tools","id":"at_discovery","role":"developer","tools":[ + {"type":"additional_tools","id":"at_00112233-4455-4677-8899-aabbccddeeff","role":"developer","tools":[ {"type":"tool_search","execution":"client"}, {"type":"namespace","name":"multi_agent_v1","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"},"defer_loading":true}]} ]}, @@ -98,8 +200,10 @@ func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { require.NoError(t, err) require.NotNil(t, result) require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", upstream.lastReq.URL.String()) - require.Equal(t, "at_discovery", gjson.GetBytes(upstream.lastBody, "input.0.id").String()) - require.JSONEq(t, gjson.GetBytes(body, "input.0").Raw, gjson.GetBytes(upstream.lastBody, "input.0").Raw) + wantID := "at_00112233445546778899aabbccddeeff" + require.Equal(t, wantID, gjson.GetBytes(upstream.lastBody, "input.0.id").String()) + require.Equal(t, "at_00112233-4455-4677-8899-aabbccddeeff", gjson.GetBytes(body, "input.0.id").String()) + require.JSONEq(t, gjson.GetBytes(body, "input.0.tools").Raw, gjson.GetBytes(upstream.lastBody, "input.0.tools").Raw) require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.1.id").Exists()) require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.2.id").Exists()) require.Equal(t, "sealed", gjson.GetBytes(upstream.lastBody, "input.2.encrypted_content").String()) diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index bbc60f7555..1d369c3f23 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -8,6 +8,8 @@ import ( "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) var codexModelMap = map[string]string{ @@ -1607,9 +1609,84 @@ func codexInputCallIDs(input []any) map[string]struct{} { return callIDs } +// Only compact UUID-shaped declaration IDs; other provider IDs are opaque. +func normalizeCodexAdditionalToolsID(id string) string { + if len(id) != 39 || !strings.HasPrefix(id, "at_") || + id[11] != '-' || id[16] != '-' || id[21] != '-' || id[26] != '-' { + return id + } + compactUUID := strings.ReplaceAll(id[3:], "-", "") + if len(compactUUID) != 32 { + return id + } + if _, err := hex.DecodeString(compactUUID); err != nil { + return id + } + return "at_" + compactUUID +} + +func codexAdditionalToolsIDMappings(input []any) map[string]string { + mappings := make(map[string]string) + for _, rawItem := range input { + item, ok := rawItem.(map[string]any) + if !ok || item["type"] != "additional_tools" { + continue + } + if id, ok := item["id"].(string); ok { + if normalizedID := normalizeCodexAdditionalToolsID(id); normalizedID != id { + mappings[id] = normalizedID + } + } + } + return mappings +} + +// The passthrough/WebSocket compatibility path must not decode and re-encode +// whole requests. Patch only declaration IDs and references to those declarations. +func normalizeCodexAdditionalToolsIDsBody(body []byte) ([]byte, bool, error) { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return body, false, nil + } + mappings := make(map[string]string) + input.ForEach(func(_, item gjson.Result) bool { + if id := item.Get("id"); item.Get("type").String() == "additional_tools" && id.Type == gjson.String { + if normalizedID := normalizeCodexAdditionalToolsID(id.Str); normalizedID != id.Str { + mappings[id.Str] = normalizedID + } + } + return true + }) + if len(mappings) == 0 { + return body, false, nil + } + items := make([]string, 0) + var patchErr error + input.ForEach(func(_, item gjson.Result) bool { + raw := item.Raw + if typ := item.Get("type").String(); typ == "additional_tools" || typ == "item_reference" { + if id := item.Get("id"); id.Type == gjson.String { + if normalizedID, mapped := mappings[id.Str]; mapped { + raw, patchErr = sjson.Set(raw, "id", normalizedID) + if patchErr != nil { + return false + } + } + } + } + items = append(items, raw) + return true + }) + if patchErr != nil { + return body, false, fmt.Errorf("normalize additional_tools ID: %w", patchErr) + } + return replaceOpenAIRawInput(body, input, items), true, nil +} + func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []any { filtered := make([]any, 0, len(input)) referenceIDMappings := codexItemReferenceIDMappings(input, opts.PreserveCallIDs) + additionalToolsIDMappings := codexAdditionalToolsIDMappings(input) inputItemIDs := codexInputItemIDs(input) inputCallIDs := codexInputCallIDs(input) for _, item := range input { @@ -1672,6 +1749,11 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an for key, value := range m { newItem[key] = value } + if id, ok := newItem["id"].(string); ok { + if normalizedID, mapped := additionalToolsIDMappings[id]; mapped { + newItem["id"] = normalizedID + } + } if id, ok := newItem["id"].(string); ok && strings.HasPrefix(strings.TrimSpace(id), "call_") { trimmedID := strings.TrimSpace(id) _, referencesExistingItem := inputItemIDs[trimmedID] @@ -1746,7 +1828,14 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an // additional_tools IDs identify declarations carried in this request, // not stored history. Removing them can change native tool discovery // into ordinary function calls even with store=false. - if !opts.PreserveReferences && typ != "additional_tools" { + if typ == "additional_tools" { + if id, ok := m["id"].(string); ok { + if normalizedID, mapped := additionalToolsIDMappings[id]; mapped { + ensureCopy() + newItem["id"] = normalizedID + } + } + } else if !opts.PreserveReferences { ensureCopy() delete(newItem, "id") } else if id, ok := m["id"].(string); ok && shouldStripOpenAIResponsesInputItemID(typ, id) { diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b7e4514405..c664e78399 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1622,6 +1622,12 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * if err != nil { return body, false, err } + if next, idsChanged, err := normalizeCodexAdditionalToolsIDsBody(normalized); err != nil { + return body, false, err + } else if idsChanged { + normalized = next + changed = true + } } if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil { return body, false, err From d085bb1a377bb42248da3bfa6d12cf205769fb56 Mon Sep 17 00:00:00 2001 From: CooCoode <5113047+CooCoode@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:51:06 +0800 Subject: [PATCH 46/85] fix(apicompat): default json_schema strict=false when converting CC to Responses Chat Completions treats a missing response_format.json_schema.strict as false, while Responses validates text.format strictly and rejects schemas without additionalProperties: false. Forwarding the format unchanged therefore turned valid requests into upstream 400 invalid_json_schema. Make the intended mode explicit by adding strict=false only when the field is absent; explicit strict values are untouched. Fixes #8760 --- .../chatcompletions_responses_test.go | 32 +++++++++++++++++++ .../internal/pkg/apicompat/response_format.go | 5 +++ 2 files changed, 37 insertions(+) diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go index b94bc5c394..21a8c05d36 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go @@ -445,6 +445,38 @@ func TestChatCompletionsToResponses_ResponseFormatJsonSchema(t *testing.T) { }`, string(resp.Text.Format)) } +func TestChatCompletionsToResponses_ResponseFormatJsonSchemaDefaultsStrictFalse(t *testing.T) { + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Return structured JSON"`)}}, + ResponseFormat: json.RawMessage(`{ + "type":"json_schema", + "json_schema":{ + "name":"answer", + "schema":{ + "type":"object", + "properties":{"ok":{"type":"boolean"}}, + "required":["ok"] + } + } + }`), + } + + resp, err := ChatCompletionsToResponses(req) + require.NoError(t, err) + require.NotNil(t, resp.Text) + assert.JSONEq(t, `{ + "type":"json_schema", + "name":"answer", + "schema":{ + "type":"object", + "properties":{"ok":{"type":"boolean"}}, + "required":["ok"] + }, + "strict":false + }`, string(resp.Text.Format)) +} + func TestChatCompletionsToResponses_ImageURL(t *testing.T) { content := `[{"type":"text","text":"Describe this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc123"}}]` req := &ChatCompletionsRequest{ diff --git a/backend/internal/pkg/apicompat/response_format.go b/backend/internal/pkg/apicompat/response_format.go index afb5c3e2fd..ce12311102 100644 --- a/backend/internal/pkg/apicompat/response_format.go +++ b/backend/internal/pkg/apicompat/response_format.go @@ -23,6 +23,11 @@ func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessag return raw } schema["type"] = rawJSONString("json_schema") + // Chat Completions defaults strict to false while Responses defaults to strict, + // so make the intended mode explicit to avoid the upstream rejecting the schema. + if _, ok := schema["strict"]; !ok { + schema["strict"] = json.RawMessage("false") + } out, err := json.Marshal(schema) if err != nil { From c54ebd4f124e88ece35dcc97cff9266ad4d61090 Mon Sep 17 00:00:00 2001 From: wc4440222 <199748891+wc4440222@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:16:28 +0800 Subject: [PATCH 47/85] fix(kimi): parse new monthly quota plan and clear absent window snapshots Kimi For Coding now ships two response shapes: - Legacy plans: limits[].detail (5h counts) + top-level usage (weekly pool). - New plans (Go/Plus/Pro): usages.limit_5h / limit_7d / limit_month_total / limit_month_code reported as used_ratio (0-1) with reset_time. There is no top-level usage block, so the monthly pool was never parsed and the monthly quota was invisible in the account list. parseKimiUsageTiers now understands usages.* (used_ratio x100, monthly takes the larger of total/code with the earlier reset), keeps the legacy usage block as a fallback, and prefers usages.limit_7d over legacy weekly counts so weekly is not emitted twice. Snapshot writes also stopped clearing windows that disappear from the response: extra updates are JSONB merges, so not writing a window keeps its previous value forever. After a plan change the old weekly percentage froze (observed 13 days) and the account page kept showing an expired 7D window. Callers now write explicit nils for absent 5h/weekly/monthly windows. cnQuotaHasMonthlyWindow includes Kimi so threshold pre-pause and the 429 cooldown snapshot consider the monthly window too. --- .../account_scheduling_threshold_eval.go | 10 +- .../service/cn_provider_quota_service.go | 105 +++++++++++++++++- backend/internal/service/cn_providers_test.go | 90 +++++++++++++++ 3 files changed, 199 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/account_scheduling_threshold_eval.go b/backend/internal/service/account_scheduling_threshold_eval.go index 951629658e..24c45d9a99 100644 --- a/backend/internal/service/account_scheduling_threshold_eval.go +++ b/backend/internal/service/account_scheduling_threshold_eval.go @@ -375,9 +375,15 @@ func cnProviderThresholdCandidates(account *Account, provider string) []*account return candidates } -// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。 +// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、 +// Command Code 与 Kimi 新套餐)。 func cnQuotaHasMonthlyWindow(provider string) bool { - return provider == PlatformOpenCodeGo || provider == PlatformCommandCode + switch provider { + case PlatformOpenCodeGo, PlatformCommandCode, PlatformKimi: + return true + default: + return false + } } func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate { diff --git a/backend/internal/service/cn_provider_quota_service.go b/backend/internal/service/cn_provider_quota_service.go index 6bbeddec52..46c013d98a 100644 --- a/backend/internal/service/cn_provider_quota_service.go +++ b/backend/internal/service/cn_provider_quota_service.go @@ -272,6 +272,11 @@ func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, accou result.CredentialValid = true updates := cnQuotaExtraUpdates(provider, tiers, now) + // 只对 5h/weekly/monthly 三档通吃的供应商清理缺席窗口;Command Code 与 + // Cline 走各自的取舍(抓取失败时保留月度),不在这里处理。 + if provider == PlatformKimi || provider == PlatformZhipu || provider == PlatformMiniMax || provider == PlatformOpenCodeGo { + clearAbsentCNQuotaWindows(provider, tiers, updates) + } if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil { slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", provider, "error", err) } else { @@ -379,13 +384,22 @@ func zhipuQuotaHost(baseURL string) string { // parseKimiUsageTiers 解析 Kimi For Coding 的 /usages 响应。 // -// - limits[].detail.{limit,remaining,resetTime} → 5h 窗口(取首个 detail) -// - usage.{limit,remaining,resetTime} → 周窗口 +// Kimi 目前并存两种套餐形态: // -// utilization = (limit-remaining)/limit*100。 +// - 老套餐(5h + 7d):limits[].detail.{limit,remaining,resetTime} → 5h +// (取首个 detail),顶层 usage.{limit,remaining,resetTime} → 周窗口, +// utilization = (limit-remaining)/limit*100。 +// - 新套餐(5h + 月度):不再有顶层 usage,改由 usages.limit_5h / +// usages.limit_7d / usages.limit_month_total / usages.limit_month_code +// 以 used_ratio(0-1)+ reset_time 上报。月度 total 与 code 任一耗尽都会 +// 限流,因此 monthly 取两者较大用量、较早重置时间。 +// +// 两者同时出现时 used_ratio 优先(比 counts 更贴近官方口径),顶层 usage 仅兜底; +// usages.limit_5h 只在 limits[] 没有 detail 时补位,避免重复产出 5h 档。 func parseKimiUsageTiers(body []byte) []CNQuotaTier { var tiers []CNQuotaTier + hasFiveHour := false if limits := gjson.GetBytes(body, "limits"); limits.IsArray() { limits.ForEach(func(_, item gjson.Result) bool { detail := item.Get("detail") @@ -407,11 +421,21 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier { UsedPercent: util, ResetAt: cnNormalizeResetTime(detail.Get("resetTime").Value()), }) + hasFiveHour = true return false // 取首个 detail 作为 5h 窗口 }) } + if !hasFiveHour { + if tier, ok := kimiUsedRatioTier(body, "limit_5h", "5h"); ok { + tiers = append(tiers, tier) + hasFiveHour = true + } + } - if usage := gjson.GetBytes(body, "usage"); usage.Exists() { + // 周窗口:usages.limit_7d 优先,顶层 usage(老套餐单数)兜底。 + if tier, ok := kimiUsedRatioTier(body, "limit_7d", "weekly"); ok { + tiers = append(tiers, tier) + } else if usage := gjson.GetBytes(body, "usage"); usage.Exists() { limit, _ := cnParseF64(usage.Get("limit").Value()) remaining, _ := cnParseF64(usage.Get("remaining").Value()) used := limit - remaining @@ -429,9 +453,53 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier { }) } + // 月度限额(新套餐):total 与 code 任一耗尽都会限流 → 取较大用量; + // 重置时间取较早者(先恢复可用额度,避免过度停调)。 + total, hasTotal := kimiUsedRatioTier(body, "limit_month_total", "monthly") + code, hasCode := kimiUsedRatioTier(body, "limit_month_code", "monthly") + if hasTotal || hasCode { + monthly := CNQuotaTier{Window: "monthly"} + if hasTotal { + monthly = total + } + if hasCode && (!hasTotal || code.UsedPercent > monthly.UsedPercent) { + monthly.UsedPercent = code.UsedPercent + } + if hasTotal && hasCode && code.ResetAt != "" && + (monthly.ResetAt == "" || code.ResetAt < monthly.ResetAt) { + monthly.ResetAt = code.ResetAt + } + tiers = append(tiers, monthly) + } + return tiers } +// kimiUsedRatioTier 解析 usages..{used_ratio,reset_time} 为窗口档位。 +// used_ratio 是 0-1 比例,输出换算为百分比;键缺失或不可解析返回 false。 +func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) { + node := gjson.GetBytes(body, "usages."+key) + if !node.Exists() { + return CNQuotaTier{}, false + } + ratioNode := node.Get("used_ratio") + if !ratioNode.Exists() { + return CNQuotaTier{}, false + } + ratio, ok := cnParseF64(ratioNode.Value()) + if !ok { + return CNQuotaTier{}, false + } + if ratio < 0 { + ratio = 0 + } + return CNQuotaTier{ + Window: window, + UsedPercent: ratio * 100, + ResetAt: cnNormalizeResetTime(node.Get("reset_time").Value()), + }, true +} + // parseMiniMaxUsageTiers 解析 MiniMax Token Plan / Coding Plan remains 响应。 // // 只取 model_name == "general"(编程套餐),跳过 video。字段是剩余百分比, @@ -671,6 +739,35 @@ func cnQuotaExtraUpdates(provider string, tiers []CNQuotaTier, now time.Time) ma return updates } +// clearAbsentCNQuotaWindows 把本次探测缺席的窗口显式写 nil(JSONB 合并语义下等于 +// 移除按键):账号 extra 的更新走 `extra || $1`,只"不写"会保留旧值。上游改套餐 +// (Kimi 老套餐 7d → 新套餐月度)后旧窗口不再上报,不清理就会把切换前的用量永久 +// 冻结在快照里(生产实测冻结 13 天,列表一直显示过期的 7D 用量)。 +// +// 仅供 5h/weekly/monthly 三档通吃的供应商调用;Command Code / Cline 有自己的 +// 取舍(周期端点抓取失败时保留月度值),不在此列。 +func clearAbsentCNQuotaWindows(provider string, tiers []CNQuotaTier, updates map[string]any) { + present := make(map[string]CNQuotaTier, len(tiers)) + for _, tier := range tiers { + present[tier.Window] = tier + } + for _, window := range []struct{ name, used, reset string }{ + {"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset}, + {"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset}, + {"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset}, + } { + tier, ok := present[window.name] + if !ok { + updates[cnExtraKey(provider, window.used)] = nil + updates[cnExtraKey(provider, window.reset)] = nil + continue + } + if tier.ResetAt == "" { + updates[cnExtraKey(provider, window.reset)] = nil + } + } +} + // parseOpenCodeGoUsageTiers 解析 OpenCode Go GET /usage 响应。 // // 结构对齐 cc-switch extractor: diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 61fea87a5a..48470382fd 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -107,6 +107,72 @@ func TestParseKimiUsageTiers_LimitZero(t *testing.T) { require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) } +// TestParseKimiUsageTiers_MonthlyPlan 新套餐形态(5h + 月度限额):不再有顶层 +// usage,改由 usages.limit_5h / limit_month_total / limit_month_code 以 +// used_ratio(0-1)+ reset_time 上报。monthly 取两条月度键的较大用量 + 较早重置。 +func TestParseKimiUsageTiers_MonthlyPlan(t *testing.T) { + t.Parallel() + body := []byte(`{ + "limits": [{ + "window": {"duration": 300, "timeUnit": "TIME_UNIT_MINUTE"}, + "detail": {"limit": "100", "used": "10", "remaining": "90", "resetTime": "2026-11-13T16:10:29.523075Z"} + }], + "usages": { + "limit_5h": {"used_ratio": 0.0982, "reset_time": "2026-11-13T16:10:28Z"}, + "limit_month_total": {"used_ratio": 0.6564, "reset_time": "2026-11-26T00:00:00Z"}, + "limit_month_code": {"used_ratio": 0.6252, "reset_time": "2026-11-26T00:00:00Z"} + } + }`) + tiers := parseKimiUsageTiers(body) + require.Len(t, tiers, 2, "新套餐应为 5h + monthly,且不得产出已废弃的 weekly") + + require.Equal(t, "5h", tiers[0].Window) + require.InDelta(t, 10.0, tiers[0].UsedPercent, 1e-9, "5h 用 limits[].detail 的绝对计数") + require.Equal(t, "2026-11-13T16:10:29Z", tiers[0].ResetAt) + + require.Equal(t, "monthly", tiers[1].Window) + require.InDelta(t, 65.64, tiers[1].UsedPercent, 1e-9, "used_ratio 0-1 换算为百分比") + require.Equal(t, "2026-11-26T00:00:00Z", tiers[1].ResetAt) +} + +// TestParseKimiUsageTiers_MonthlyPicksMaxUsage total/code 任一耗尽都会限流: +// monthly 取较大用量;重置时间取较早者(先恢复额度,避免过度停调)。 +func TestParseKimiUsageTiers_MonthlyPicksMaxUsage(t *testing.T) { + t.Parallel() + body := []byte(`{"usages":{ + "limit_month_total":{"used_ratio":0.4,"reset_time":"2026-11-26T00:00:00Z"}, + "limit_month_code":{"used_ratio":0.9,"reset_time":"2026-11-20T00:00:00Z"}}}`) + tiers := parseKimiUsageTiers(body) + require.Len(t, tiers, 1) + require.Equal(t, "monthly", tiers[0].Window) + require.InDelta(t, 90.0, tiers[0].UsedPercent, 1e-9) + require.Equal(t, "2026-11-20T00:00:00Z", tiers[0].ResetAt) + + onlyCode := parseKimiUsageTiers([]byte(`{"usages":{"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-20T00:00:00Z"}}}`)) + require.Len(t, onlyCode, 1) + require.Equal(t, "monthly", onlyCode[0].Window) + require.InDelta(t, 50.0, onlyCode[0].UsedPercent, 1e-9) +} + +// TestParseKimiUsageTiers_LegacyWithUsedRatio 老套餐(顶层 usage)同时携带 +// usages.limit_7d 时,weekly 以 used_ratio 为准、不重复产出 weekly 档。 +func TestParseKimiUsageTiers_LegacyWithUsedRatio(t *testing.T) { + t.Parallel() + body := []byte(`{ + "usage": {"limit": "100", "remaining": "80", "resetTime": "2026-10-07T05:04:39.713183Z"}, + "usages": { + "limit_5h": {"used_ratio": 0, "reset_time": "2026-10-04T11:04:38Z"}, + "limit_7d": {"used_ratio": 0.203912, "reset_time": "2026-10-07T05:04:38Z"} + } + }`) + tiers := parseKimiUsageTiers(body) + require.Len(t, tiers, 2) + require.Equal(t, "5h", tiers[0].Window) + require.Equal(t, "weekly", tiers[1].Window) + require.InDelta(t, 20.3912, tiers[1].UsedPercent, 1e-9) + require.Equal(t, "2026-10-07T05:04:38Z", tiers[1].ResetAt) +} + // TestParseZhipuTokenTiers_UnitClassification 显式 unit(3=5h / 6=weekly)优先分类, // 不能被 reset 时间排序覆盖(周期末尾周窗口会更早重置)。 func TestParseZhipuTokenTiers_UnitClassification(t *testing.T) { @@ -231,6 +297,30 @@ func TestCNQuotaExtraUpdates(t *testing.T) { require.Equal(t, now.Format(time.RFC3339), updates["kimi_usage_updated_at"]) } +// 缺席窗口必须显式写 nil:extra 走 JSONB 合并(`extra || $1`),只"不写"会保留 +// 旧值。Kimi 老套餐 → 新套餐(月度)切换后 weekly 不再上报,不清理就会把切换前 +// 的用量永久冻结在快照里(生产实测冻结 13 天)。 +func TestCNQuotaExtraUpdatesClearsAbsentWindows(t *testing.T) { + t.Parallel() + now := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC) + tiers := []CNQuotaTier{ + {Window: "5h", UsedPercent: 10, ResetAt: "2026-11-13T16:10:29Z"}, + {Window: "monthly", UsedPercent: 65.64, ResetAt: "2026-11-26T00:00:00Z"}, + } + updates := cnQuotaExtraUpdates(PlatformKimi, tiers, now) + clearAbsentCNQuotaWindows(PlatformKimi, tiers, updates) + + value, present := updates["kimi_weekly_used_percent"] + require.True(t, present, "缺席的 weekly 必须显式出现在更新里") + require.Nil(t, value) + _, resetPresent := updates["kimi_weekly_reset_at"] + require.True(t, resetPresent) + + require.Equal(t, 10.0, updates["kimi_5h_used_percent"]) + require.Equal(t, 65.64, updates["kimi_monthly_used_percent"]) + require.Equal(t, "2026-11-26T00:00:00Z", updates["kimi_monthly_reset_at"]) +} + func TestParseOpenCodeGoUsageTiers(t *testing.T) { t.Parallel() body := []byte(`{ From a0a03be96d81fd1aae4a989500cd4a2752212e80 Mon Sep 17 00:00:00 2001 From: Zeeland Date: Sat, 14 Nov 2026 03:22:38 +0800 Subject: [PATCH 48/85] fix(openai): normalize additional Codex context on HTTP Responses --- .../handler/openai_gateway_handler.go | 4 +- .../internal/handler/openai_page_context.go | 25 +++- .../handler/openai_page_context_test.go | 132 ++++++++++++++++-- 3 files changed, 145 insertions(+), 16 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index f70bce78b2..d2b07bc31a 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -489,9 +489,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } else if changed { body = cappedBody } - if normalizedBody, changed := normalizeCodexPageContext(body); changed { + if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed { body = normalizedBody - reqLog.Info("openai.codex_page_context_normalized", + reqLog.Info("openai.codex_untrusted_context_normalized", zap.String("normalization", "call_output_to_user_message"), ) } diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index c61e830425..7313852f6a 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -11,10 +11,10 @@ import ( var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`) -// Desktop injects page snapshots as standalone outputs, without a model tool call. -// Keep them as untrusted user text, including on history replay and mixed bootstrap turns. -func normalizeCodexPageContext(body []byte) ([]byte, bool) { - if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(body) { +// Codex injects external context as standalone outputs, without a model tool call. +// Use the legacy user-message representation for HTTP Responses interoperability. +func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { + if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) { return body, false } var request map[string]json.RawMessage @@ -46,15 +46,19 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) { } } name, output := readString("name"), readString("output") - if !validCodexPageContext(name, output) { + if !validCodexUntrustedContext(name, output) { continue } + text := "" + output + "" + if validCodexPageContext(name, output) { + text = "\n" + output + "\n" + } message := map[string]any{ "type": "message", "role": "user", "content": []map[string]string{{ "type": "input_text", - "text": "\n" + output + "\n", + "text": text, }}, } encoded, err := json.Marshal(message) @@ -79,6 +83,15 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) { return encoded, true } +func validCodexUntrustedContext(name, output string) bool { + switch name { + case "browser_info", "goal_objective", "untrusted_context": + return strings.TrimSpace(output) != "" + default: + return validCodexPageContext(name, output) + } +} + func validCodexPageContext(name, output string) bool { if name == "codex_apps_open_page" { return validCodexPageSnapshot(output) diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index dccdc6fd82..2eb204ac90 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -34,7 +34,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { require.Equal(t, 400, w.Code) require.Contains(t, w.Body.String(), "function_call_output requires call_id") - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) w = httptest.NewRecorder() c, _ = gin.CreateTestContext(w) @@ -49,14 +49,130 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { require.False(t, item.Get("id").Exists()) } require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String()) - again, changed := normalizeCodexPageContext(got) + again, changed := normalizeCodexUntrustedContext(got) require.False(t, changed) require.Equal(t, got, again) } +func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) { + // AdditionalContextToolOutput derives names from caller-provided context keys. + // Codex 0.169.0 enables this representation by default (openai/codex#60487). + for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + t.Run(name, func(t *testing.T) { + output := "external context\nline two" + body := pageContextRequest(t, pageContextItem(name, output), + map[string]any{"role": "user", "content": "continue"}) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.False(t, c.Writer.Written()) + item := gjson.GetBytes(got, "input.0") + require.Equal(t, "message", item.Get("type").String()) + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, ""+output+"", item.Get("content.0.text").String()) + require.False(t, item.Get("call_id").Exists()) + require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String()) + again, changed := normalizeCodexUntrustedContext(got) + require.False(t, changed) + require.Equal(t, got, again) + }) + } +} + +func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) { + for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, override := range []map[string]any{ + {"call_id": "call_real"}, + {"call_id": nil}, + {"call_id": 42}, + {"namespace": "other"}, + {"namespace": nil}, + {"namespace": 42}, + {"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}}, + {"output": " "}, + {"output": nil}, + } { + item := pageContextItem(name, "context") + for key, value := range override { + item[key] = value + } + body := pageContextRequest(t, item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed, "name=%s override=%v", name, override) + require.Equal(t, body, got) + } + item := pageContextItem(name, "context") + delete(item, "namespace") + body := pageContextRequest(t, item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed) + require.Equal(t, body, got) + } + // Recognized external context cannot make an unrelated tool result valid. + body := pageContextRequest(t, pageContextItem("browser_info", "tab"), + pageContextItem("read_file", "result")) + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.Equal(t, 400, w.Code) + + // Keep historical calls, prior response and exact numeric metadata intact. + body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`) + got, changed = normalizeCodexUntrustedContext(body) + require.True(t, changed) + require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String()) + require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw) + for _, index := range []string{"input.0", "input.1"} { + require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw) + } +} + +func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) { + names := []string{"browser_info", "goal_objective", "untrusted_context"} + for _, callID := range []string{"", " \t\n"} { + items := make([]any, 0, len(names)) + for _, name := range names { + item := pageContextItem(name, "context for "+name) + item["call_id"] = callID + delete(item, "id") + items = append(items, item) + } + got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...)) + require.True(t, changed) + require.Len(t, gjson.GetBytes(got, "input").Array(), len(names)) + for i, item := range gjson.GetBytes(got, "input").Array() { + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, "context for "+names[i]+"", item.Get("content.0.text").String()) + } + } +} + +func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) { + for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, body := range []string{ + `{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`, + `{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`, + } { + got, changed := normalizeCodexUntrustedContext([]byte(body)) + require.False(t, changed) + require.Equal(t, body, string(got)) + } + } +} + func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) { body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String()) require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw) @@ -66,7 +182,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T badTool := pageContextItem("read_file", "result") body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool) - got, changed = normalizeCodexPageContext(body) + got, changed = normalizeCodexUntrustedContext(body) require.True(t, changed) require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID) } @@ -77,7 +193,7 @@ func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) { {"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "test"}, } { body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) got, _ = normalizeCodexAutomationBootstrap(got) got, _ = normalizeCodexDelegationBootstrap(got) @@ -89,7 +205,7 @@ func TestNormalizeCodexPageContextMultipart(t *testing.T) { first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello` second := "Companion Page snapshot part 2 of 2:\n" + ` world"}` body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second)) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first) require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second) @@ -119,7 +235,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) item := pageContextItem("codex_apps_open_page", `{"page_id":null}`) item[tc.key] = tc.value body := pageContextRequest(t, item) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.False(t, changed) require.Equal(t, body, got) }) @@ -128,7 +244,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) `{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`, `{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`, } { - got, changed := normalizeCodexPageContext([]byte(body)) + got, changed := normalizeCodexUntrustedContext([]byte(body)) require.False(t, changed) require.Equal(t, body, string(got)) } From a293214977a5536fed44b50e46a39e37032ec7bd Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:59:23 +0800 Subject: [PATCH 49/85] chore(ci): bump Go toolchain to 1.27.4 for GO-2026-6859 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit backend-security 的 govulncheck 现在报标准库漏洞: Vulnerability #1: GO-2026-6859 HTTP/1 server crash due to MaxBytesReader header race in net/http Found in: net/http@go1.27.3 Fixed in: net/http@go1.27.4 仓库把 Go 版本固定在 1.27.3(go.mod + workflow 硬断言 + 三个 Dockerfile), 所以所有 PR 的 backend-security 都会失败,与具体改动无关。 同步升级 8 处版本点: - backend/go.mod:go 1.27.3 → 1.27.4 - security-scan.yml / backend-ci.yml(两处)/ release.yml:go1.27.4 断言 - Dockerfile / deploy/Dockerfile / backend/Dockerfile:golang:1.27.4-alpine - DEV_GUIDE.md 的 CI 要求说明同步更新 验证:GOTOOLCHAIN=go1.27.4 go build ./... 通过, GOTOOLCHAIN=go1.27.4 go test -tags unit ./internal/service/ 针对性用例通过。 --- .github/workflows/backend-ci.yml | 4 ++-- .github/workflows/release.yml | 2 +- .github/workflows/security-scan.yml | 2 +- DEV_GUIDE.md | 2 +- Dockerfile | 2 +- backend/Dockerfile | 2 +- backend/go.mod | 2 +- deploy/Dockerfile | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index d1b420aa94..751f1fb0fd 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -35,7 +35,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Unit tests working-directory: backend run: make test-unit @@ -75,7 +75,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: golangci-lint uses: golangci/golangci-lint-action@v9 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9f2ef5dd7d..b5780a6be5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -137,7 +137,7 @@ jobs: check-latest: false cache: false - name: Verify Go version - run: go version | grep -q 'go1.27.3' + run: go version | grep -q 'go1.27.4' - name: Restore target-specific Go cache id: go-cache uses: actions/cache/restore@v6 diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 703e10354a..19893aae97 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -23,7 +23,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Run govulncheck working-directory: backend run: | diff --git a/DEV_GUIDE.md b/DEV_GUIDE.md index 2f440d0f62..f01d59e48c 100644 --- a/DEV_GUIDE.md +++ b/DEV_GUIDE.md @@ -53,7 +53,7 @@ npm install -g pnpm ### CI 要求 -- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 +- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 - 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml` ### 本地测试命令 diff --git a/Dockerfile b/Dockerfile index 0242d6f13e..0c9e438850 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.3-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.21 ARG POSTGRES_IMAGE=postgres:18-alpine ARG GOPROXY=https://goproxy.cn,direct diff --git a/backend/Dockerfile b/backend/Dockerfile index 40e228cd37..52bcb43dcc 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.2-alpine +FROM golang:1.27.4-alpine WORKDIR /app diff --git a/backend/go.mod b/backend/go.mod index 91db5d03b4..8163fbea14 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/Wei-Shaw/sub2api -go 1.27.3 +go 1.27.4 require ( entgo.io/ent v0.14.5 diff --git a/deploy/Dockerfile b/deploy/Dockerfile index d5c580b466..e0e8fbf030 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -7,7 +7,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.2-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.20 ARG GOPROXY=https://goproxy.cn,direct ARG GOSUMDB=sum.golang.google.cn From 694d09379b24d93a4a57ad5dda1c0bf8d940707d Mon Sep 17 00:00:00 2001 From: wc4440222 <199748891+wc4440222@users.noreply.github.com> Date: Sat, 14 Nov 2026 05:26:59 +0800 Subject: [PATCH 50/85] fix(kimi): harden new-plan quota parsing and absent-window cleanup Follow-up hardening on the new-plan monthly quota support. All changes are backward compatible with the legacy response shape. 1. Empty parse is not "unlimited" A 2xx response that yields zero recognized windows now counts as a failed probe: the previous snapshot is kept and no success timestamp is written. Without this, the absent-window cleanup would write 5h/weekly/monthly as nil, and the scheduler - which reads "no window" as "no quota limit" - would clear the pre-emptive pause and let an exhausted account back into rotation. 2. Reject malformed window values instead of fabricating 0% limits[].detail now requires limit > 0 and remaining in [0, limit]; the legacy top-level usage block gets the same check. `{"detail":{}}` or limit=0 used to produce a "0% used" tier, masking real exhaustion. 3. used_ratio must be a finite value in [0, 1] Out-of-range ratios (e.g. a provider switching to percent units) produced 6500%-style values; NaN/Inf were accepted by ParseFloat. cnParseF64 now rejects non-finite results for every caller. 4. Monthly reset takes the later window total and code are two independent rate-limit windows. Taking the earlier reset (11-20) released the account while the other window was still exhausted (11-26). Use the later reset: better to stay parked slightly longer than to hit upstream 429. 5. Zhipu percentage is validated Missing/invalid/out-of-range percentage no longer defaults to 0, which had the same fabricated-window problem now that absent-window cleanup also covers zhipu. Tests: added rejection matrices for malformed Kimi and Zhipu payloads, legal edge-value cases (0%, full usage, single window, integer JSON), and the dual-monthly-window reset assertions. Existing legacy-shape expectations are unchanged except the limit=0 case, which must now yield no tier. --- .../service/cn_provider_quota_service.go | 121 +++++++++++------- backend/internal/service/cn_providers_test.go | 93 +++++++++++++- 2 files changed, 163 insertions(+), 51 deletions(-) diff --git a/backend/internal/service/cn_provider_quota_service.go b/backend/internal/service/cn_provider_quota_service.go index 46c013d98a..1257cf40e3 100644 --- a/backend/internal/service/cn_provider_quota_service.go +++ b/backend/internal/service/cn_provider_quota_service.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "log/slog" + "math" "net/http" "sort" "strconv" @@ -268,6 +269,18 @@ func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, accou result.PlanLevel = strings.TrimSpace(gjson.GetBytes(bodyBytes, "current_subscribe_title").String()) } result.Tiers = tiers + // 2xx 但一个可用窗口都解析不出来,通常意味着上游报文改版/字段改名,而不是 + // 「额度无限」。必须按失败处理:保留旧快照、不写成功时间;否则下面的缺席 + // 清理会把 5h/weekly/monthly 全写 nil,调度层看到「没有窗口」就会解除预停调, + // 让仍处于耗尽的账号回池撞 429。 + if len(tiers) == 0 { + result.Error = fmt.Sprintf( + "quota response for %s contains no recognized usage window (upstream schema may have changed); keeping the previous snapshot", + provider) + slog.Warn("cn_quota_no_recognized_window", + "account_id", account.ID, "provider", provider, "http_status", resp.StatusCode) + return result, nil + } result.Success = true result.CredentialValid = true @@ -406,23 +419,22 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier { if !detail.Exists() { return true } - limit, _ := cnParseF64(detail.Get("limit").Value()) - remaining, _ := cnParseF64(detail.Get("remaining").Value()) - used := limit - remaining - if used < 0 { - used = 0 - } - var util float64 - if limit > 0 { - util = used / limit * 100 + // 字段节点存在不等于数值可信:limit/remaining 必须可解析、limit>0、 + // remaining 落在 [0, limit],否则跳过该条(`{"detail":{}}` 或 limit=0 + // 不能产出一个「已用 0%」的伪窗口,那会掩盖真实的额度耗尽状态)。 + limit, okLimit := cnParseF64(detail.Get("limit").Value()) + remaining, okRemaining := cnParseF64(detail.Get("remaining").Value()) + if !okLimit || !okRemaining || limit <= 0 || remaining < 0 || remaining > limit { + return true } + util := (limit - remaining) / limit * 100 tiers = append(tiers, CNQuotaTier{ Window: "5h", UsedPercent: util, ResetAt: cnNormalizeResetTime(detail.Get("resetTime").Value()), }) hasFiveHour = true - return false // 取首个 detail 作为 5h 窗口 + return false // 取首个有效 detail 作为 5h 窗口 }) } if !hasFiveHour { @@ -436,38 +448,34 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier { if tier, ok := kimiUsedRatioTier(body, "limit_7d", "weekly"); ok { tiers = append(tiers, tier) } else if usage := gjson.GetBytes(body, "usage"); usage.Exists() { - limit, _ := cnParseF64(usage.Get("limit").Value()) - remaining, _ := cnParseF64(usage.Get("remaining").Value()) - used := limit - remaining - if used < 0 { - used = 0 + limit, okLimit := cnParseF64(usage.Get("limit").Value()) + remaining, okRemaining := cnParseF64(usage.Get("remaining").Value()) + if okLimit && okRemaining && limit > 0 && remaining >= 0 && remaining <= limit { + tiers = append(tiers, CNQuotaTier{ + Window: "weekly", + UsedPercent: (limit - remaining) / limit * 100, + ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()), + }) } - var util float64 - if limit > 0 { - util = used / limit * 100 - } - tiers = append(tiers, CNQuotaTier{ - Window: "weekly", - UsedPercent: util, - ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()), - }) } - // 月度限额(新套餐):total 与 code 任一耗尽都会限流 → 取较大用量; - // 重置时间取较早者(先恢复可用额度,避免过度停调)。 + // 月度限额(新套餐):total 与 code 是两个**独立**的限流窗口,任一耗尽都会限流。 + // 用量取两者较大值;重置时间取**较晚**者——取较早会在另一个窗口仍耗尽时提前 + // 解除预停调(例如 total 到 11-26 才恢复、code 到 11-20 恢复)。宁可晚回池, + // 不可提前撞 429。 total, hasTotal := kimiUsedRatioTier(body, "limit_month_total", "monthly") code, hasCode := kimiUsedRatioTier(body, "limit_month_code", "monthly") if hasTotal || hasCode { - monthly := CNQuotaTier{Window: "monthly"} - if hasTotal { - monthly = total - } - if hasCode && (!hasTotal || code.UsedPercent > monthly.UsedPercent) { - monthly.UsedPercent = code.UsedPercent - } - if hasTotal && hasCode && code.ResetAt != "" && - (monthly.ResetAt == "" || code.ResetAt < monthly.ResetAt) { - monthly.ResetAt = code.ResetAt + monthly := total + if !hasTotal { + monthly = code + } else if hasCode { + if code.UsedPercent > monthly.UsedPercent { + monthly.UsedPercent = code.UsedPercent + } + if code.ResetAt != "" && (monthly.ResetAt == "" || code.ResetAt > monthly.ResetAt) { + monthly.ResetAt = code.ResetAt + } } tiers = append(tiers, monthly) } @@ -476,7 +484,7 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier { } // kimiUsedRatioTier 解析 usages..{used_ratio,reset_time} 为窗口档位。 -// used_ratio 是 0-1 比例,输出换算为百分比;键缺失或不可解析返回 false。 +// used_ratio 是 0-1 比例,输出换算为百分比;键缺失、不可解析或越界返回 false。 func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) { node := gjson.GetBytes(body, "usages."+key) if !node.Exists() { @@ -490,8 +498,10 @@ func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) { if !ok { return CNQuotaTier{}, false } - if ratio < 0 { - ratio = 0 + // 必须落在上游声明区间 [0,1]:越界值(例如把百分数 65 直接塞进 used_ratio) + // 会算出 6500%,NaN/Inf 同理不可信。 + if ratio < 0 || ratio > 1 { + return CNQuotaTier{}, false } return CNQuotaTier{ Window: window, @@ -642,9 +652,11 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { if limitType != "TOKENS_LIMIT" && limitType != "CREDIT_LIMIT" { return true } - percentage := 0.0 - if p, ok := cnParseF64(item.Get("percentage").Value()); ok { - percentage = p + // percentage 缺失/非数字/NaN/越界时不能默认 0:那会产出一个「已用 0%」的 + // 合法窗口,既掩盖真实耗尽状态,也会被缺席清理当成有效快照落库。 + percentage, okPercentage := cnParseF64(item.Get("percentage").Value()) + if !okPercentage || percentage < 0 || percentage > 100 { + return true } var ( resetMs int64 @@ -815,24 +827,37 @@ func parseOpenCodeGoUsageTiers(body []byte) []CNQuotaTier { // cnParseF64 把 JSON 数值或字符串解析为 float64(兼容 "100" 与 100)。 func cnParseF64(raw any) (float64, bool) { + var value float64 switch v := raw.(type) { case float64: - return v, true + value = v case float32: - return float64(v), true + value = float64(v) case int: - return float64(v), true + value = float64(v) case int64: - return float64(v), true + value = float64(v) case json.Number: f, err := v.Float64() - return f, err == nil + if err != nil { + return 0, false + } + value = f case string: f, err := strconv.ParseFloat(strings.TrimSpace(v), 64) - return f, err == nil + if err != nil { + return 0, false + } + value = f default: return 0, false } + // strconv.ParseFloat 接受 "NaN"/"Inf",JSON 的 1e999 也会得到 +Inf; + // 这类值参与百分比与阈值比较会让停调判定失效,一律视为不可解析。 + if math.IsNaN(value) || math.IsInf(value, 0) { + return 0, false + } + return value, true } // cnNormalizeResetTime 把上游重置时间(ISO8601 字符串 / 秒级 / 毫秒级数字)归一化为 diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 48470382fd..fefd4d062c 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -103,8 +103,9 @@ func TestParseKimiUsageTiers_LimitZero(t *testing.T) { t.Parallel() body := []byte(`{"limits":[{"detail":{"limit":0,"remaining":0,"resetTime":"2026-08-14T15:00:00Z"}}]}`) tiers := parseKimiUsageTiers(body) - require.Len(t, tiers, 1) - require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) + // limit=0 无法计算利用率:不能产出「已用 0%」的伪窗口(那会把额度耗尽 + // 显示成完全没用),该条目应被跳过。 + require.Len(t, tiers, 0) } // TestParseKimiUsageTiers_MonthlyPlan 新套餐形态(5h + 月度限额):不再有顶层 @@ -146,7 +147,16 @@ func TestParseKimiUsageTiers_MonthlyPicksMaxUsage(t *testing.T) { require.Len(t, tiers, 1) require.Equal(t, "monthly", tiers[0].Window) require.InDelta(t, 90.0, tiers[0].UsedPercent, 1e-9) - require.Equal(t, "2026-11-20T00:00:00Z", tiers[0].ResetAt) + // total 与 code 是两个独立限流窗口:reset 必须取较晚者,否则 code 先到期的 + // 11-20 会让仍处于 40% 的 total 窗口提前放行。 + require.Equal(t, "2026-11-26T00:00:00Z", tiers[0].ResetAt) + + // 两窗口同为 100% 时也不得取更早的 reset。 + bothFull := parseKimiUsageTiers([]byte(`{"usages":{ + "limit_month_total":{"used_ratio":1,"reset_time":"2026-11-26T00:00:00Z"}, + "limit_month_code":{"used_ratio":1,"reset_time":"2026-11-20T00:00:00Z"}}}`)) + require.Len(t, bothFull, 1) + require.Equal(t, "2026-11-26T00:00:00Z", bothFull[0].ResetAt) onlyCode := parseKimiUsageTiers([]byte(`{"usages":{"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-20T00:00:00Z"}}}`)) require.Len(t, onlyCode, 1) @@ -321,6 +331,83 @@ func TestCNQuotaExtraUpdatesClearsAbsentWindows(t *testing.T) { require.Equal(t, "2026-11-26T00:00:00Z", updates["kimi_monthly_reset_at"]) } +// TestParseKimiUsageTiers_RejectsMalformedWindows 受损/改版结构不得产出伪窗口。 +// 这类窗口一旦被当成有效快照落库,缺席清理会把其他窗口写成 nil, +// 调度层看到「没有窗口」就会解除预停调。 +func TestParseKimiUsageTiers_RejectsMalformedWindows(t *testing.T) { + t.Parallel() + cases := map[string]struct { + body []byte + }{ + "empty object": {[]byte(`{}`)}, + "empty detail": {[]byte(`{"limits":[{"detail":{}}]}`)}, + "limit zero": {[]byte(`{"limits":[{"detail":{"limit":0,"remaining":0}}]}`)}, + "remaining exceeds": {[]byte(`{"limits":[{"detail":{"limit":100,"remaining":200}}]}`)}, + "limit not a number": {[]byte(`{"limits":[{"detail":{"limit":"abc","remaining":"1"}}]}`)}, + "empty usage": {[]byte(`{"usage":{}}`)}, + "ratio out of range": {[]byte(`{"usages":{"limit_5h":{"used_ratio":65}}}`)}, + "ratio NaN": {[]byte(`{"usages":{"limit_5h":{"used_ratio":"NaN"}}}`)}, + "ratio negative": {[]byte(`{"usages":{"limit_5h":{"used_ratio":-0.2}}}`)}, + "renamed top level key": {[]byte(`{"limits_v2":[{"detail":{"limit":100,"remaining":50}}]}`)}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + tiers := parseKimiUsageTiers(tc.body) + require.Empty(t, tiers, "受损结构不得产出窗口:%s", string(tc.body)) + }) + } +} + +// TestParseKimiUsageTiers_KeepsLegalEdgeValues 合法边界(0%、满额、单窗口、整数)不得被误伤。 +func TestParseKimiUsageTiers_KeepsLegalEdgeValues(t *testing.T) { + t.Parallel() + // remaining == limit → 合法的 0%。 + tiers := parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":100}}]}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) + + // remaining == 0 → 100%。 + tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":0}}]}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9) + + // used_ratio == 0 / 1 同样合法。 + tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":0}}}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) + + tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":1}}}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9) + + // 首个 detail 坏、后续合法 → 采用首个有效条目。 + tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{}},{"detail":{"limit":100,"remaining":60}}]}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 40.0, tiers[0].UsedPercent, 1e-9) +} + +// TestParseZhipuTokenTiers_SkipsMissingPercentage percentage 缺失/非法不得伪造 0% 窗口。 +func TestParseZhipuTokenTiers_SkipsMissingPercentage(t *testing.T) { + t.Parallel() + cases := map[string]struct { + body string + wantTiers int + }{ + "missing percentage": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3}]}`, 0}, + "non numeric": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":"abc"}]}`, 0}, + "negative": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":-5}]}`, 0}, + "over 100": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":120}]}`, 0}, + "legal zero": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":0}]}`, 1}, + "legal five hour": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":42}]}`, 1}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + tiers := parseZhipuTokenTiers(gjson.Parse(tc.body)) + require.Len(t, tiers, tc.wantTiers, "输入:%s", tc.body) + }) + } +} + func TestParseOpenCodeGoUsageTiers(t *testing.T) { t.Parallel() body := []byte(`{ From f1394a1ab4ab22e2e221e0df20a6d898074567f0 Mon Sep 17 00:00:00 2001 From: Henglie Date: Sat, 14 Nov 2026 13:09:07 +0800 Subject: [PATCH 51/85] fix(web): stop caching settings-injected HTML Settings are injected into index.html and the page also embeds a per-request CSP nonce. A cached document can paint stale branding, and answering If-None-Match with 304 while minting a new nonce makes the browser reuse HTML whose nonce no longer matches the CSP header. Mark every settings-injected HTML response as uncacheable for browsers and CDN edges, and only allow 304 when the response has no nonce. --- backend/internal/web/embed_on.go | 21 ++- backend/internal/web/embed_test.go | 122 ++++++++++++++++-- backend/internal/web/html_cache_headers.go | 18 +++ .../internal/web/html_cache_headers_test.go | 40 ++++++ 4 files changed, 186 insertions(+), 15 deletions(-) create mode 100644 backend/internal/web/html_cache_headers.go create mode 100644 backend/internal/web/html_cache_headers_test.go diff --git a/backend/internal/web/embed_on.go b/backend/internal/web/embed_on.go index 03e5e5f50e..d401e7fde9 100644 --- a/backend/internal/web/embed_on.go +++ b/backend/internal/web/embed_on.go @@ -149,18 +149,23 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { // Check cache first cached := s.cache.Get() if cached != nil { - // Check If-None-Match for 304 response - if match := c.GetHeader("If-None-Match"); match == cached.ETag { - c.Status(http.StatusNotModified) - c.Abort() - return + // A matching ETag is only enough for 304 when the response has no + // per-request nonce. Otherwise the browser would reuse HTML carrying a + // stale nonce that no longer matches the CSP header of this request. + if nonce == "" { + if match := c.GetHeader("If-None-Match"); match == cached.ETag { + applyHTMLNoCacheHeaders(c.Writer.Header()) + c.Status(http.StatusNotModified) + c.Abort() + return + } } // Replace nonce placeholder with actual nonce before serving content := replaceNoncePlaceholder(cached.Content, nonce) c.Header("ETag", cached.ETag) - c.Header("Cache-Control", "no-cache") // Must revalidate + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", content) c.Abort() return @@ -173,6 +178,7 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { settings, err := s.settings.GetPublicSettingsForInjection(ctx) if err != nil { // Fallback: serve without injection + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", s.baseHTML) c.Abort() return @@ -181,6 +187,7 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { settingsJSON, err := json.Marshal(settings) if err != nil { // Fallback: serve without injection + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", s.baseHTML) c.Abort() return @@ -196,7 +203,7 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { if cached != nil { c.Header("ETag", cached.ETag) } - c.Header("Cache-Control", "no-cache") + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", content) c.Abort() } diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go index 75dac764fb..97b9c948d8 100644 --- a/backend/internal/web/embed_test.go +++ b/backend/internal/web/embed_test.go @@ -352,7 +352,7 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { assert.True(t, strings.HasSuffix(etag, `"`)) }) - t.Run("returns_304_for_matching_etag", func(t *testing.T) { + t.Run("returns_304_only_when_no_nonce_is_present", func(t *testing.T) { provider := &mockSettingsProvider{ settings: map[string]string{"test": "value"}, } @@ -360,12 +360,8 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { server, err := NewFrontendServer(provider) require.NoError(t, err) - // Use a real router for proper 304 handling + // No nonce in context means the cached body has no per-request part. router := gin.New() - router.Use(func(c *gin.Context) { - c.Set(middleware.CSPNonceKey, "test-nonce") - c.Next() - }) router.Use(server.Middleware()) // First request to populate cache and get ETag @@ -383,9 +379,47 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { assert.Equal(t, http.StatusNotModified, w2.Code) assert.Empty(t, w2.Body.String()) + assertNoStoreHTMLHeaders(t, w2.Header()) }) - t.Run("sets_cache_control_header", func(t *testing.T) { + t.Run("serves_fresh_html_when_cached_nonce_is_stale", func(t *testing.T) { + provider := &mockSettingsProvider{ + settings: map[string]string{"test": "value"}, + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(middleware.CSPNonceKey, c.GetHeader("X-Test-Nonce")) + c.Next() + }) + router.Use(server.Middleware()) + + w1 := httptest.NewRecorder() + req1 := httptest.NewRequest(http.MethodGet, "/", nil) + req1.Header.Set("X-Test-Nonce", "first-nonce") + router.ServeHTTP(w1, req1) + etag := w1.Header().Get("ETag") + require.NotEmpty(t, etag) + assert.Contains(t, w1.Body.String(), `nonce="first-nonce"`) + + // The document embeds the request nonce, so a matching ETag must not + // turn this into a 304 that reuses the previous nonce. + w2 := httptest.NewRecorder() + req2 := httptest.NewRequest(http.MethodGet, "/", nil) + req2.Header.Set("X-Test-Nonce", "second-nonce") + req2.Header.Set("If-None-Match", etag) + router.ServeHTTP(w2, req2) + + assert.Equal(t, http.StatusOK, w2.Code) + assert.Contains(t, w2.Body.String(), `nonce="second-nonce"`) + assert.NotContains(t, w2.Body.String(), `nonce="first-nonce"`) + assertNoStoreHTMLHeaders(t, w2.Header()) + }) + + t.Run("sets_no_store_cache_headers", func(t *testing.T) { provider := &mockSettingsProvider{ settings: map[string]string{"test": "value"}, } @@ -400,7 +434,7 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { server.serveIndexHTML(c) - assert.Equal(t, "no-cache", w.Header().Get("Cache-Control")) + assertNoStoreHTMLHeaders(t, w.Header()) }) t.Run("fallback_on_settings_error", func(t *testing.T) { @@ -427,6 +461,78 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { }) } +func assertNoStoreHTMLHeaders(t *testing.T, header http.Header) { + t.Helper() + assert.Equal(t, "no-cache, no-store, must-revalidate", header.Get("Cache-Control")) + assert.Equal(t, "no-cache", header.Get("Pragma")) + assert.Equal(t, "0", header.Get("Expires")) + assert.Equal(t, "no-store", header.Get("CDN-Cache-Control")) + assert.Equal(t, "no-store", header.Get("Surrogate-Control")) +} + +func TestFrontendServer_NoStoreHeadersOnEveryHTMLPath(t *testing.T) { + t.Run("cache_hit", func(t *testing.T) { + provider := &mockSettingsProvider{ + settings: map[string]string{"test": "value"}, + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + w1 := httptest.NewRecorder() + c1, _ := gin.CreateTestContext(w1) + c1.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c1.Set(middleware.CSPNonceKey, "nonce1") + server.serveIndexHTML(c1) + require.Equal(t, http.StatusOK, w1.Code) + + w2 := httptest.NewRecorder() + c2, _ := gin.CreateTestContext(w2) + c2.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c2.Set(middleware.CSPNonceKey, "nonce2") + server.serveIndexHTML(c2) + + assert.Equal(t, http.StatusOK, w2.Code) + assertNoStoreHTMLHeaders(t, w2.Header()) + }) + + t.Run("settings_error_fallback", func(t *testing.T) { + provider := &mockSettingsProvider{ + err: context.DeadlineExceeded, + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c.Set(middleware.CSPNonceKey, "nonce123") + server.serveIndexHTML(c) + + assert.Equal(t, http.StatusOK, w.Code) + assertNoStoreHTMLHeaders(t, w.Header()) + }) + + t.Run("settings_marshal_error_fallback", func(t *testing.T) { + provider := &mockSettingsProvider{ + settings: make(chan struct{}), + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c.Set(middleware.CSPNonceKey, "nonce123") + server.serveIndexHTML(c) + + assert.Equal(t, http.StatusOK, w.Code) + assertNoStoreHTMLHeaders(t, w.Header()) + }) +} + func TestFrontendServer_InvalidateCache(t *testing.T) { t.Run("invalidates_cache", func(t *testing.T) { provider := &mockSettingsProvider{ diff --git a/backend/internal/web/html_cache_headers.go b/backend/internal/web/html_cache_headers.go new file mode 100644 index 0000000000..ade6c35987 --- /dev/null +++ b/backend/internal/web/html_cache_headers.go @@ -0,0 +1,18 @@ +//go:build embed || unit + +package web + +import "net/http" + +// applyHTMLNoCacheHeaders marks settings-injected HTML as uncacheable at every +// layer: browser memory/disk cache, back/forward cache (browsers skip bfcache +// for no-store responses) and CDN edge caches. Settings are injected into the +// document, so a stale copy would paint outdated branding until the next +// revalidation. +func applyHTMLNoCacheHeaders(header http.Header) { + header.Set("Cache-Control", "no-cache, no-store, must-revalidate") + header.Set("Pragma", "no-cache") + header.Set("Expires", "0") + header.Set("CDN-Cache-Control", "no-store") + header.Set("Surrogate-Control", "no-store") +} diff --git a/backend/internal/web/html_cache_headers_test.go b/backend/internal/web/html_cache_headers_test.go new file mode 100644 index 0000000000..e762b3ddb9 --- /dev/null +++ b/backend/internal/web/html_cache_headers_test.go @@ -0,0 +1,40 @@ +//go:build unit + +package web + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestApplyHTMLNoCacheHeaders(t *testing.T) { + header := http.Header{} + + applyHTMLNoCacheHeaders(header) + + assert.Equal(t, "no-cache, no-store, must-revalidate", header.Get("Cache-Control")) + assert.Equal(t, "no-cache", header.Get("Pragma")) + assert.Equal(t, "0", header.Get("Expires")) + assert.Equal(t, "no-store", header.Get("CDN-Cache-Control")) + assert.Equal(t, "no-store", header.Get("Surrogate-Control")) +} + +func TestApplyHTMLNoCacheHeadersReplacesExistingValues(t *testing.T) { + header := http.Header{ + "Cache-Control": {"public, max-age=3600"}, + "Pragma": {"cache"}, + "Expires": {"Thu, 01 Jan 2099 00:00:00 GMT"}, + "CDN-Cache-Control": {"max-age=3600"}, + "Surrogate-Control": {"max-age=3600"}, + } + + applyHTMLNoCacheHeaders(header) + + assert.Equal(t, "no-cache, no-store, must-revalidate", header.Get("Cache-Control")) + assert.Equal(t, "no-cache", header.Get("Pragma")) + assert.Equal(t, "0", header.Get("Expires")) + assert.Equal(t, "no-store", header.Get("CDN-Cache-Control")) + assert.Equal(t, "no-store", header.Get("Surrogate-Control")) +} From 4114fedd1892ee8b14aec40c716f5685edf9663a Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:50:14 +0800 Subject: [PATCH 52/85] fix(ratelimit): lift Anthropic Fable model limit when the 7d_oi window recovers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7d_oi 窗口耗尽时 persistAnthropicFableWindowLimit 会给账号写入 model_rate_limits["claude-fable-5"],冷却到窗口重置时间(最长 7 天)。 写入之后没有任何路径会撤销它: - samplePassiveUsageFromHeaders / syncActiveToPassive 只更新 passive_usage_7d_oi_utilization,不与 model_rate_limits 联动; - applyAnthropicFableSchedulingThreshold 只设不清; - UpdateSessionWindow 的自动清除只看账号级 RateLimitResetAt, 而窗口耗尽分支刻意不设它(账号对其他模型仍然可调度)。 于是用户用重置卡让上游额度提前归零后,本地仍按旧的 rate_limit_reset_at 返回 503 No available accounts supporting model,只能人工删 extra 或点“清除限流”。 修复: - 上游明确回报 7d_oi utilization 低于阈值(重置卡生效/窗口滚动)、且该窗口未处于 rejected/exceeded 时,撤销窗口耗尽写入的限流;缺失数据一律不动,缺失不等于 0; - 只清 claude-fable-5 这一个 scope(新增 AccountRepository.ClearModelRateLimit, jsonb 单键删除),不影响其他模型与并发新写入的限流; - 只清 reason 为 anthropic_7d_oi_window_exhausted 的记录:credits required 与 管理端阈值来源语义不同,不能被窗口用量顺手清掉; - 写库成功后才同步本实例的账号快照;写库失败保持原样,避免本实例放行而调度快照仍拦截。 两个观测点都接上:请求响应头的被动采样,以及管理端主动刷新额度。 --- backend/internal/repository/account_repo.go | 43 ++++ backend/internal/server/api_contract_test.go | 4 + backend/internal/service/account_service.go | 3 + .../service/account_service_delete_test.go | 4 + .../internal/service/account_usage_service.go | 19 +- .../account_usage_service_fable_test.go | 2 +- .../account_usage_session_window_test.go | 4 +- .../service/admin_service_clear_error_test.go | 4 + .../service/gateway_multiplatform_test.go | 4 + .../service/gemini_multiplatform_test.go | 4 + backend/internal/service/model_rate_limit.go | 24 +++ .../service/ratelimit_fable_recovery_test.go | 195 ++++++++++++++++++ backend/internal/service/ratelimit_service.go | 50 +++++ .../service/ratelimit_service_clear_test.go | 4 + .../service/ratelimit_session_window_test.go | 4 + 15 files changed, 362 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/ratelimit_fable_recovery_test.go diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 733ff9034b..097c0a8fc2 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -2690,6 +2690,49 @@ func (r *accountRepository) ClearModelRateLimits(ctx context.Context, id int64) return nil } +// ClearModelRateLimit 删除 model_rate_limits 中指定的单个 scope。 +// 与 ClearModelRateLimits 的全量清除不同,这里只解封一个模型窗口, +// 不会把其他模型或并发新写入的限流一起抹掉。 +func (r *accountRepository) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + if strings.TrimSpace(scope) == "" { + return nil + } + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearModelRateLimit(ctx, id, scope) + } + client := clientFromContext(ctx, r.client) + result, err := client.ExecContext( + ctx, + `UPDATE accounts SET + extra = jsonb_set( + COALESCE(extra, '{}'::jsonb), + '{model_rate_limits}'::text[], + COALESCE(extra->'model_rate_limits', '{}'::jsonb) - $1::text, + true + ), + updated_at = NOW() + WHERE id = $2 AND deleted_at IS NULL`, + strings.TrimSpace(scope), + id, + ) + if err != nil { + return err + } + + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected == 0 { + return service.ErrAccountNotFound + } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue clear model rate limit scope failed: account=%d err=%v", id, err) + } + r.syncSchedulerAccountSnapshot(ctx, id) + return nil +} + func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { builder := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 81d3d91854..df8bf1dd80 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -2047,6 +2047,10 @@ func (s *stubAccountRepo) ClearModelRateLimits(ctx context.Context, id int64) er return errors.New("not implemented") } +func (s *stubAccountRepo) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return errors.New("not implemented") +} + func (s *stubAccountRepo) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { return errors.New("not implemented") } diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 7980a5c447..e33d0b13f1 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -108,6 +108,9 @@ type AccountRepository interface { ClearRateLimit(ctx context.Context, id int64) error ClearAntigravityQuotaScopes(ctx context.Context, id int64) error ClearModelRateLimits(ctx context.Context, id int64) error + // ClearModelRateLimit 只清除指定 scope 的模型级限流,用于单个模型窗口恢复后 + // 定向解封,不影响其他模型与并发生效的限流。 + ClearModelRateLimit(ctx context.Context, id int64, scope string) error UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error // UpdateSessionWindowEnd 仅更新 5h 窗口的结束时间,不动 start / status。 // 用于 active poll 拿到新 ResetsAt 后回写,避免覆盖请求路径上记录的 status。 diff --git a/backend/internal/service/account_service_delete_test.go b/backend/internal/service/account_service_delete_test.go index ed65c25c1b..80c4ff6e6d 100644 --- a/backend/internal/service/account_service_delete_test.go +++ b/backend/internal/service/account_service_delete_test.go @@ -195,6 +195,10 @@ func (s *accountRepoStub) ClearModelRateLimits(ctx context.Context, id int64) er panic("unexpected ClearModelRateLimits call") } +func (s *accountRepoStub) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + panic("unexpected ClearModelRateLimit call") +} + func (s *accountRepoStub) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { panic("unexpected UpdateSessionWindow call") } diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index f9a8904e6c..fc5eb46f13 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -483,8 +483,9 @@ func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *A // 4. 添加窗口统计(有独立缓存,1 分钟) s.addWindowStats(ctx, account, usage) - // 5. 将主动查询结果同步到被动缓存,下次 passive 加载即为最新值 - s.syncActiveToPassive(ctx, account.ID, usage) + // 5. 将主动查询结果同步到被动缓存,下次 passive 加载即为最新值; + // 其中还会在上游明确给出已回落的 7d_oi 用量时撤销窗口耗尽写入的模型级限流。 + s.syncActiveToPassive(ctx, account, usage) // 6. 上游 usage API 目前不一定下发 Fable 7d 窗口;缺失时回填被动采样 // (7d_oi 响应头)的数据,避免主动查询后 7d F 进度条丢失。 @@ -715,7 +716,15 @@ func buildPassiveUsageWindow(extra map[string]any, utilKey, resetKey string) *Us // syncActiveToPassive 将主动查询的最新数据回写到 Extra 被动缓存, // 这样下次被动加载时能看到最新值。 -func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID int64, usage *UsageInfo) { +// +// 主动查询是“重置卡生效后额度已恢复”最直接的观测点:这里在拿到 API 明确回报的 +// 7d_oi 用量后,顺手撤销窗口耗尽写入的模型级限流。回填被动采样发生在调用方, +// 因此本函数的 usage.SevenDayFable 一定是上游返回值,不会把旧采样当成恢复依据。 +func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, account *Account, usage *UsageInfo) { + if account == nil { + return + } + accountID := account.ID extraUpdates := make(map[string]any, 4) if usage.FiveHour != nil { @@ -748,6 +757,10 @@ func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID slog.Warn("sync_active_to_passive_session_window_end_failed", "account_id", accountID, "error", err) } } + + if usage.SevenDayFable != nil { + recoverAnthropicFableWindowLimit(ctx, s.accountRepo, account, usage.SevenDayFable.Utilization/100) + } } func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Account, force bool) (*UsageInfo, error) { diff --git a/backend/internal/service/account_usage_service_fable_test.go b/backend/internal/service/account_usage_service_fable_test.go index 60f2e9c79f..43329ee972 100644 --- a/backend/internal/service/account_usage_service_fable_test.go +++ b/backend/internal/service/account_usage_service_fable_test.go @@ -106,7 +106,7 @@ func TestSyncActiveToPassive_WritesFableExtras(t *testing.T) { }, } - svc.syncActiveToPassive(t.Context(), 1, usage) + svc.syncActiveToPassive(t.Context(), &Account{ID: 1}, usage) select { case updates := <-repo.updateExtraCh: diff --git a/backend/internal/service/account_usage_session_window_test.go b/backend/internal/service/account_usage_session_window_test.go index 779a5974fd..bca6a456d4 100644 --- a/backend/internal/service/account_usage_session_window_test.go +++ b/backend/internal/service/account_usage_session_window_test.go @@ -97,7 +97,7 @@ func TestSyncActiveToPassive_WritesFiveHourSessionWindowEnd(t *testing.T) { repo := &sessionWindowSyncRepo{} svc := &AccountUsageService{accountRepo: repo} resetsAt := time.Now().Add(3 * time.Hour).UTC().Truncate(time.Second) - svc.syncActiveToPassive(context.Background(), 42, &UsageInfo{ + svc.syncActiveToPassive(context.Background(), &Account{ID: 42}, &UsageInfo{ FiveHour: &UsageProgress{ Utilization: 53, ResetsAt: &resetsAt, @@ -123,7 +123,7 @@ func TestSyncActiveToPassive_SkipsSessionWindowEndWhenResetMissing(t *testing.T) repo := &sessionWindowSyncRepo{} svc := &AccountUsageService{accountRepo: repo} - svc.syncActiveToPassive(context.Background(), 99, &UsageInfo{ + svc.syncActiveToPassive(context.Background(), &Account{ID: 99}, &UsageInfo{ FiveHour: &UsageProgress{Utilization: 10}, }) diff --git a/backend/internal/service/admin_service_clear_error_test.go b/backend/internal/service/admin_service_clear_error_test.go index 41418c4f9a..d4ae092e29 100644 --- a/backend/internal/service/admin_service_clear_error_test.go +++ b/backend/internal/service/admin_service_clear_error_test.go @@ -48,6 +48,10 @@ func (r *accountRepoStubForClearAccountError) ClearModelRateLimits(ctx context.C return nil } +func (r *accountRepoStubForClearAccountError) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} + func (r *accountRepoStubForClearAccountError) ClearTempUnschedulable(ctx context.Context, id int64) error { r.clearTempUnschedCalls++ r.account.TempUnschedulableUntil = nil diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index badb2427cf..604999fd4c 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -208,6 +208,10 @@ func (m *mockAccountRepoForPlatform) ClearAntigravityQuotaScopes(ctx context.Con func (m *mockAccountRepoForPlatform) ClearModelRateLimits(ctx context.Context, id int64) error { return nil } + +func (m *mockAccountRepoForPlatform) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} func (m *mockAccountRepoForPlatform) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { return nil } diff --git a/backend/internal/service/gemini_multiplatform_test.go b/backend/internal/service/gemini_multiplatform_test.go index 3c26f8f2ca..63ac4a6f51 100644 --- a/backend/internal/service/gemini_multiplatform_test.go +++ b/backend/internal/service/gemini_multiplatform_test.go @@ -172,6 +172,10 @@ func (m *mockAccountRepoForGemini) ClearAntigravityQuotaScopes(ctx context.Conte func (m *mockAccountRepoForGemini) ClearModelRateLimits(ctx context.Context, id int64) error { return nil } + +func (m *mockAccountRepoForGemini) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} func (m *mockAccountRepoForGemini) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { return nil } diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go index fc181de078..1081f4846f 100644 --- a/backend/internal/service/model_rate_limit.go +++ b/backend/internal/service/model_rate_limit.go @@ -244,3 +244,27 @@ func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt ti extra[modelRateLimitsKey] = limits account.Extra = extra } + +// clearAccountModelRateLimitSnapshot 从本账号对象的 Extra 快照中删除指定 scope, +// 让当前实例立刻停止跳过该模型,而不必等下一次快照重建。 +// 与 setAccountModelRateLimitSnapshot 一样写时复制,不修改可能共享的旧 map。 +func clearAccountModelRateLimitSnapshot(account *Account, scope string) { + if account == nil || strings.TrimSpace(scope) == "" { + return + } + oldLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any) + if !ok { + return + } + if _, exists := oldLimits[scope]; !exists { + return + } + limits := make(map[string]any, len(oldLimits)) + maps.Copy(limits, oldLimits) + delete(limits, scope) + + extra := make(map[string]any, len(account.Extra)) + maps.Copy(extra, account.Extra) + extra[modelRateLimitsKey] = limits + account.Extra = extra +} diff --git a/backend/internal/service/ratelimit_fable_recovery_test.go b/backend/internal/service/ratelimit_fable_recovery_test.go new file mode 100644 index 0000000000..dab59c9222 --- /dev/null +++ b/backend/internal/service/ratelimit_fable_recovery_test.go @@ -0,0 +1,195 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// 上游 7d_oi 窗口耗尽会给账号写入 model_rate_limits["claude-fable-5"],冷却到窗口重置时间。 +// 如果期间用户用重置卡让上游额度提前归零,本地原本没有任何撤销路径:请求一直在本地 +// 被判为 model_rate_limited,直到旧的 rate_limit_reset_at 到期为止。 +// +// 下面锁定恢复规则:只有上游**明确**回报 7d_oi 用量回落到耗尽线以下、且已有记录来自 +// 窗口耗尽时,才按单 key 撤销;缺失数据、积分不足、窗口仍被拒、以及其它模型都不受影响。 + +type fableRecoveryRepo struct { + sessionWindowMockRepo + clearedScopes []string + clearErr error +} + +func (r *fableRecoveryRepo) ClearModelRateLimit(_ context.Context, _ int64, scope string) error { + r.clearedScopes = append(r.clearedScopes, scope) + return r.clearErr +} + +func newFableRecoveryAccount(reason string, extraLimits map[string]any) *Account { + limits := map[string]any{ + anthropicFableRateLimitKey: map[string]any{ + "rate_limited_at": time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339), + "rate_limit_reset_at": time.Now().Add(3 * 24 * time.Hour).UTC().Format(time.RFC3339), + "reason": reason, + }, + } + for scope, payload := range extraLimits { + limits[scope] = payload + } + return &Account{ + ID: 42, + Platform: PlatformAnthropic, + Type: AccountTypeOAuth, + Extra: map[string]any{modelRateLimitsKey: limits}, + } +} + +func fableUsageHeaders(utilization string, rejected bool) http.Header { + headers := http.Header{} + headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") + if rejected { + headers.Set("anthropic-ratelimit-unified-7d_oi-status", "rejected") + } + if utilization != "" { + headers.Set("anthropic-ratelimit-unified-7d_oi-utilization", utilization) + } + headers.Set("anthropic-ratelimit-unified-7d_oi-reset", strconv.FormatInt(time.Now().Add(7*24*time.Hour).Unix(), 10)) + return headers +} + +func TestPassiveUsageClearsExhaustedFableLimitAfterQuotaReset(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2"), + "前提:窗口耗尽后 Fable 请求被本地拦截") + + // 重置卡生效:上游回报该窗口 0%。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes, + "必须只按 claude-fable-5 这一个 scope 撤销") + require.False(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2"), + "本实例的账号快照要同步解除,否则当前实例仍会继续跳过该账号") +} + +func TestPassiveUsageKeepsFableLimitWhenUtilizationMissing(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + // 缺失不等于 0:上游没给 7d_oi 用量时不得撤销。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("", false)) + + require.Empty(t, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2")) +} + +func TestPassiveUsageKeepsFableLimitWhileWindowStillRejected(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + // 窗口仍是 rejected 时,即使 utilization 因为口径差异低于 1.0 也不能撤销。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0.5", true)) + + require.Empty(t, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2")) +} + +func TestPassiveUsageKeepsFableLimitWhenUtilizationStillHigh(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0.98", false)) + + require.Empty(t, repo.clearedScopes, "利用率仍接近耗尽线时不撤销") +} + +func TestPassiveUsageKeepsCreditsRequiredLimit(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableCreditsRequiredReason, nil) + + // 积分不足(credits required)与窗口耗尽语义不同,不能被窗口用量顺手清掉。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Empty(t, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2")) +} + +func TestPassiveUsageKeepsOtherModelLimitsWhenRecoveringFable(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + otherLimit := map[string]any{ + "rate_limited_at": time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), + "rate_limit_reset_at": time.Now().Add(6 * time.Hour).UTC().Format(time.RFC3339), + "reason": anthropicFableWindowReason, + } + account := newFableRecoveryAccount(anthropicFableWindowReason, map[string]any{ + "claude-opus-4-1": otherLimit, + }) + + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes) + require.False(t, account.isRateLimitActiveForKey(anthropicFableRateLimitKey)) + require.True(t, account.isRateLimitActiveForKey("claude-opus-4-1"), + "其它模型的限流必须原样保留") +} + +func TestPassiveUsageKeepsLimitWhenClearFails(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{clearErr: errors.New("db unavailable")} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2"), + "写库失败时不能只改内存快照,否则本实例放行而调度快照仍拦截") +} + +// 主动用量刷新(管理端「刷新额度」)是另一个观测点:上游 usage API 明确给出 +// 已回落的 7d_oi 用量时同样要撤销;API 没给这个窗口时保持原状。 +func TestSyncActiveToPassiveClearsExhaustedFableLimit(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &AccountUsageService{accountRepo: repo} + + t.Run("api reports recovery", func(t *testing.T) { + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + usage := &UsageInfo{SevenDayFable: &UsageProgress{Utilization: 3}} + + svc.syncActiveToPassive(ctx, account, usage) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes) + require.False(t, account.isRateLimitActiveForKey(anthropicFableRateLimitKey)) + }) + + t.Run("api omits the fable window", func(t *testing.T) { + repo.clearedScopes = nil + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + usage := &UsageInfo{SevenDayFable: nil} + + svc.syncActiveToPassive(ctx, account, usage) + + require.Empty(t, repo.clearedScopes, "上游未下发该窗口时不能当成 0") + require.True(t, account.isRateLimitActiveForKey(anthropicFableRateLimitKey)) + }) +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 61c065ec0d..0fbbba262d 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -1598,8 +1598,49 @@ func (s *RateLimitService) persistAnthropicExhaustedWindowLimit(ctx context.Cont const ( anthropicFableWindowReason = "anthropic_7d_oi_window_exhausted" anthropicFableCreditsRequiredReason = "anthropic_fable_credits_required" + + // anthropicFableWindowRecoveredUtilization 是判定 7d_oi 窗口已恢复的用量上限。 + // 上游明确回报利用率低于该值(重置卡生效、窗口滚动)时撤销窗口耗尽写入的限流; + // 留出余量避免贴着 1.0 的采样来回抖动。 + anthropicFableWindowRecoveredUtilization = 0.95 ) +// recoverAnthropicFableWindowLimit 在上游明确回报 7d_oi 用量已回落到耗尽线以下时, +// 撤销此前由窗口耗尽写入的 claude-fable-5 模型级限流。 +// +// 三条约束: +// 1. 只有明确拿到利用率才判断;缺失一律不动,缺失不等于 0; +// 2. 只撤销 anthropicFableWindowReason 来源的限流——积分不足(credits required) +// 与管理端阈值来源的语义不同,不能被窗口用量顺手清掉; +// 3. 只清 claude-fable-5 这一个 scope,不影响其他模型与并发新写入的限流。 +func recoverAnthropicFableWindowLimit(ctx context.Context, repo AccountRepository, account *Account, utilization float64) bool { + if repo == nil || account == nil || account.ID <= 0 { + return false + } + if utilization < 0 || utilization >= anthropicFableWindowRecoveredUtilization { + return false + } + if !account.isRateLimitActiveForKey(anthropicFableRateLimitKey) { + return false + } + if account.modelRateLimitReason(anthropicFableRateLimitKey) != anthropicFableWindowReason { + return false + } + if err := repo.ClearModelRateLimit(ctx, account.ID, anthropicFableRateLimitKey); err != nil { + slog.Warn("anthropic_fable_window_recovery_clear_failed", + "account_id", account.ID, + "utilization", utilization, + "error", err) + return false + } + clearAccountModelRateLimitSnapshot(account, anthropicFableRateLimitKey) + slog.Info("anthropic_fable_window_recovered", + "account_id", account.ID, + "scope", anthropicFableRateLimitKey, + "utilization", utilization) + return true +} + // persistAnthropicFableCreditsRequired handles Anthropic's credits_required // response for Fable. Although the upstream status is 429, this response only // says that the organization cannot use Fable; marking the whole account rate @@ -2157,9 +2198,11 @@ func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, ac } } // 7d_oi (Fable 专属 7d 窗口) utilization(0-1 小数) + var fableUtil *float64 if utilStr := headers.Get("anthropic-ratelimit-unified-7d_oi-utilization"); utilStr != "" { if util, err := strconv.ParseFloat(utilStr, 64); err == nil { extraUpdates["passive_usage_7d_oi_utilization"] = util + fableUtil = &util } } // 7d_oi reset timestamp @@ -2177,6 +2220,13 @@ func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, ac slog.Warn("passive_usage_update_failed", "account_id", account.ID, "error", err) } } + + // 上游已明确回报 7d_oi 用量回落到耗尽线以下(额度重置或窗口滚动)时, + // 撤销此前窗口耗尽写入的模型级限流,避免重置卡生效后仍被本地拦到原 + // rate_limit_reset_at 才解封。窗口仍处于 rejected/exceeded 时不撤销。 + if fableUtil != nil && !isAnthropicWindowRejected(headers, "7d_oi") && !isAnthropicWindowExceeded(headers, "7d_oi") { + recoverAnthropicFableWindowLimit(ctx, s.accountRepo, account, *fableUtil) + } } // ClearRateLimit 清除账号的限流状态 diff --git a/backend/internal/service/ratelimit_service_clear_test.go b/backend/internal/service/ratelimit_service_clear_test.go index e8d312f9b9..c3f4538cbb 100644 --- a/backend/internal/service/ratelimit_service_clear_test.go +++ b/backend/internal/service/ratelimit_service_clear_test.go @@ -57,6 +57,10 @@ func (r *rateLimitClearRepoStub) ClearModelRateLimits(ctx context.Context, id in return r.clearModelRateLimitErr } +func (r *rateLimitClearRepoStub) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} + func (r *rateLimitClearRepoStub) ClearTempUnschedulable(ctx context.Context, id int64) error { r.clearTempUnschedCalls++ return r.clearTempUnschedulableErr diff --git a/backend/internal/service/ratelimit_session_window_test.go b/backend/internal/service/ratelimit_session_window_test.go index bf7cc2bf0a..d3de55622b 100644 --- a/backend/internal/service/ratelimit_session_window_test.go +++ b/backend/internal/service/ratelimit_session_window_test.go @@ -54,6 +54,10 @@ func (m *sessionWindowMockRepo) ClearAntigravityQuotaScopes(_ context.Context, _ func (m *sessionWindowMockRepo) ClearModelRateLimits(_ context.Context, _ int64) error { return nil } + +func (m *sessionWindowMockRepo) ClearModelRateLimit(_ context.Context, _ int64, _ string) error { + return nil +} func (m *sessionWindowMockRepo) ClearTempUnschedulable(_ context.Context, _ int64) error { return nil } From a0340d4ddeb5831e53910dc7f93c3d3fc95bfb53 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:54:32 -0800 Subject: [PATCH 53/85] fix(websearch): honor account mode on every channel-toggle platform GetWebSearchEmulationMode only read extra.web_search_emulation for anthropic and openai API key accounts and returned "default" for every other platform, although the channel form already lists zhipu, command_code, opencode_go and minimax for the same feature. Those accounts reach shouldEmulateWebSearchFor through the OpenAI gateway /v1/messages path, so "enabled" was ignored and "disabled" could not override a channel that turns the emulation on. Let every platform in the channel whitelist through the gate and extend the account and channel matrix test to them. --- backend/internal/service/account.go | 15 ++++++++++++--- .../service/gateway_websearch_emulation_test.go | 5 ++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 8899c2d70d..be94a95ed7 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -2410,10 +2410,8 @@ const ( // 三态:default(跟随渠道)/ enabled(强制开启)/ disabled(强制关闭)。 // 兼容旧 bool 值:true→enabled, false→default(并记录 debug 日志)。 func (a *Account) GetWebSearchEmulationMode() string { - // OpenAI API Key accounts reach this via /v1/messages; their upstreams - // (DeepSeek etc. over Chat Completions) have no web_search tool. if a == nil || a.Type != AccountTypeAPIKey || a.Extra == nil || - (a.Platform != PlatformAnthropic && a.Platform != PlatformOpenAI) { + !webSearchEmulationPlatformEnabled(a.Platform) { return WebSearchModeDefault } raw := a.Extra[featureKeyWebSearchEmulation] @@ -2437,6 +2435,17 @@ func (a *Account) GetWebSearchEmulationMode() string { } } +// webSearchEmulationPlatformEnabled reports whether API key accounts of the +// platform can set the account-level web search emulation mode. Keep it in sync +// with WEB_SEARCH_EMULATION_PLATFORMS in frontend/src/views/admin/ChannelsView.vue. +func webSearchEmulationPlatformEnabled(platform string) bool { + switch platform { + case PlatformAnthropic, PlatformOpenAI, PlatformZhipu, PlatformCommandCode, PlatformOpenCodeGo, PlatformMiniMax: + return true + } + return false +} + // IsCodexCLIOnlyEnabled 返回 OpenAI OAuth 账号是否启用"仅允许 Codex 官方客户端"。 // 字段:accounts.extra.codex_cli_only。 // 字段缺失或类型不正确时,按 false(关闭)处理。 diff --git a/backend/internal/service/gateway_websearch_emulation_test.go b/backend/internal/service/gateway_websearch_emulation_test.go index 0c05563f66..2577e38dcc 100644 --- a/backend/internal/service/gateway_websearch_emulation_test.go +++ b/backend/internal/service/gateway_websearch_emulation_test.go @@ -418,7 +418,10 @@ func TestShouldEmulateWebSearchFor_AccountChannelModes(t *testing.T) { settingSvc := newSettingServiceForWebSearchTest(true) groupID := int64(42) - for _, platform := range []string{PlatformOpenAI, PlatformAnthropic} { + platforms := []string{ + PlatformOpenAI, PlatformAnthropic, PlatformZhipu, PlatformCommandCode, PlatformOpenCodeGo, PlatformMiniMax, + } + for _, platform := range platforms { for _, accountType := range []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken} { for _, mode := range []string{WebSearchModeDefault, WebSearchModeEnabled, WebSearchModeDisabled} { for _, channelEnabled := range []bool{false, true} { From c45ef4116f0cb680a6fc87bb2e75d78869140e81 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:53:45 -0800 Subject: [PATCH 54/85] fix(pricing): check remote hash in background at startup Initialize waited on the remote hash fetch before the server started listening, so when the hash request hung, startup stayed blocked until the client timeout (10 s). The local price file is already loaded at that point, so the hash check and any download now run in a goroutine; the periodic scheduler is unchanged. The model-count log in Initialize reads pricingData under the read lock because a background download may replace it. --- backend/internal/service/pricing_service.go | 47 +++--- .../service/pricing_service_startup_test.go | 134 ++++++++++++++++++ 2 files changed, 162 insertions(+), 19 deletions(-) create mode 100644 backend/internal/service/pricing_service_startup_test.go diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index f973b5abef..ec5acfa335 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -343,7 +343,10 @@ func (s *PricingService) Initialize() error { // 启动定时更新 s.startUpdateScheduler() - logger.LegacyPrintf("service.pricing", "[Pricing] Service initialized with %d models", len(s.pricingData)) + s.mu.RLock() + modelCount := len(s.pricingData) + s.mu.RUnlock() + logger.LegacyPrintf("service.pricing", "[Pricing] Service initialized with %d models", modelCount) return nil } @@ -416,25 +419,10 @@ func (s *PricingService) checkAndUpdatePricing() error { return s.downloadPricingData() } - // 如果配置了哈希URL,通过远程哈希检查是否有更新 + // 如果配置了哈希URL,通过远程哈希检查是否有更新。本地文件已加载,服务已可用, + // 校验放到后台做:远端慢或不通时不挡启动与监听(fetchRemoteHash 请求挂住时会一直等到客户端超时)。 if s.cfg.Pricing.HashURL != "" { - remoteHash, err := s.fetchRemoteHash() - if err != nil { - logger.LegacyPrintf("service.pricing", "[Pricing] Failed to fetch remote hash on startup: %v", err) - return nil // 已加载本地文件,哈希获取失败不影响启动 - } - - s.mu.RLock() - localHash := s.localHash - s.mu.RUnlock() - - if localHash == "" || remoteHash != localHash { - logger.LegacyPrintf("service.pricing", "[Pricing] Remote hash differs on startup (local=%s remote=%s), downloading...", - localHash[:min(8, len(localHash))], remoteHash[:min(8, len(remoteHash))]) - if err := s.downloadPricingData(); err != nil { - logger.LegacyPrintf("service.pricing", "[Pricing] Download failed, using existing file: %v", err) - } - } + go s.checkRemoteHashOnStartup() return nil } @@ -457,6 +445,27 @@ func (s *PricingService) checkAndUpdatePricing() error { return nil } +// checkRemoteHashOnStartup 启动后在后台比对远程哈希,不同则下载;失败只记日志,沿用已加载的本地文件。 +func (s *PricingService) checkRemoteHashOnStartup() { + remoteHash, err := s.fetchRemoteHash() + if err != nil { + logger.LegacyPrintf("service.pricing", "[Pricing] Failed to fetch remote hash on startup: %v", err) + return + } + + s.mu.RLock() + localHash := s.localHash + s.mu.RUnlock() + + if localHash == "" || remoteHash != localHash { + logger.LegacyPrintf("service.pricing", "[Pricing] Remote hash differs on startup (local=%s remote=%s), downloading...", + localHash[:min(8, len(localHash))], remoteHash[:min(8, len(remoteHash))]) + if err := s.downloadPricingData(); err != nil { + logger.LegacyPrintf("service.pricing", "[Pricing] Download failed, using existing file: %v", err) + } + } +} + // syncWithRemote 与远程同步(基于哈希校验) func (s *PricingService) syncWithRemote() error { // 如果配置了哈希URL,从远程获取哈希进行比对 diff --git a/backend/internal/service/pricing_service_startup_test.go b/backend/internal/service/pricing_service_startup_test.go new file mode 100644 index 0000000000..bf0b1d14da --- /dev/null +++ b/backend/internal/service/pricing_service_startup_test.go @@ -0,0 +1,134 @@ +package service + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "os" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// blockingHashRemoteClient 的 FetchHashText 一直阻塞到 release 关闭,模拟远端不可达时等满超时。 +type blockingHashRemoteClient struct { + started chan struct{} + release chan struct{} + once sync.Once +} + +func (c *blockingHashRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) { + return nil, context.DeadlineExceeded +} + +func (c *blockingHashRemoteClient) FetchHashText(context.Context, string) (string, error) { + c.once.Do(func() { close(c.started) }) + <-c.release + return "", context.DeadlineExceeded +} + +// failingHashRemoteClient 的哈希请求立即失败,下载请求只计数。 +type failingHashRemoteClient struct { + mu sync.Mutex + hashCalls int + downloads int +} + +func (c *failingHashRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.downloads++ + return nil, errors.New("unexpected download") +} + +func (c *failingHashRemoteClient) FetchHashText(context.Context, string) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.hashCalls++ + return "", errors.New("hash endpoint unreachable") +} + +func (c *failingHashRemoteClient) counts() (hashCalls, downloads int) { + c.mu.Lock() + defer c.mu.Unlock() + return c.hashCalls, c.downloads +} + +func newStartupPricingService(t *testing.T, remote PricingRemoteClient) *PricingService { + t.Helper() + svc := NewPricingService(&config.Config{Pricing: config.PricingConfig{ + DataDir: t.TempDir(), + RemoteURL: "https://example.com/pricing.json", + HashURL: "https://example.com/pricing.sha256", + }}, remote) + require.NoError(t, os.WriteFile(svc.getPricingFilePath(), []byte(hotReloadCatalogJSON), 0644)) + return svc +} + +// 本地价格文件已在时,启动检查不得等远端哈希:远端不可达也要立即返回,价格表已可用。 +func TestPricingStartupDoesNotWaitForRemoteHash(t *testing.T) { + remote := &blockingHashRemoteClient{started: make(chan struct{}), release: make(chan struct{})} + t.Cleanup(func() { close(remote.release) }) + svc := newStartupPricingService(t, remote) + + done := make(chan error, 1) + go func() { done <- svc.checkAndUpdatePricing() }() + + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("startup must not block on the remote hash fetch") + } + require.NotNil(t, svc.GetModelPricing("remote-model"), "本地价格表启动即可用") + select { + case <-remote.started: + case <-time.After(2 * time.Second): + t.Fatal("remote hash check must still run in the background") + } +} + +// 后台哈希校验发现远端哈希不同时,仍要下载并替换价格表。 +func TestPricingStartupBackgroundCheckDownloadsWhenHashDiffers(t *testing.T) { + newBody := `{` + hotReloadModelJSON("remote-model", 3e-6, 6e-6) + `}` + newHash := fmt.Sprintf("%x", sha256.Sum256([]byte(newBody))) + remote := &stubPricingRemoteClient{body: newBody, hash: newHash} + svc := newStartupPricingService(t, remote) + + require.NoError(t, svc.checkAndUpdatePricing()) + + require.Eventually(t, func() bool { + p := svc.GetModelPricing("remote-model") + return p != nil && p.InputCostPerToken == 3e-6 + }, 2*time.Second, 10*time.Millisecond, "后台校验应下载并替换价格表") + svc.mu.RLock() + require.Equal(t, newHash, svc.localHash) + svc.mu.RUnlock() + saved, err := os.ReadFile(svc.getPricingFilePath()) + require.NoError(t, err) + require.Equal(t, newBody, string(saved)) +} + +// 后台哈希获取失败时沿用已加载的本地价格表,只记日志,不触发下载。 +func TestPricingStartupBackgroundCheckKeepsLocalDataWhenHashFetchFails(t *testing.T) { + logs, restore := captureStructuredLog(t) + defer restore() + remote := &failingHashRemoteClient{} + svc := newStartupPricingService(t, remote) + + require.NoError(t, svc.checkAndUpdatePricing()) + + require.Eventually(t, func() bool { + return logs.ContainsMessage("Failed to fetch remote hash on startup: hash endpoint unreachable") + }, 2*time.Second, 10*time.Millisecond, "哈希获取失败应记日志") + hashCalls, downloads := remote.counts() + require.Equal(t, 1, hashCalls) + require.Zero(t, downloads) + p := svc.GetModelPricing("remote-model") + require.NotNil(t, p) + require.InDelta(t, 1e-6, p.InputCostPerToken, 1e-12) +} From 2b86d2f6a023bc7d1442bc2a350cb952d3616cb6 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:53:54 -0800 Subject: [PATCH 55/85] fix(gateway): stop duplicating headers on count_tokens passthrough The count_tokens passthrough builder copies client headers under their wire casing (lowercase content-type and anthropic-version) but looked them up with the canonical-key Header.Get before filling in defaults. A client that sent them got a second canonical Content-Type and Anthropic-Version next to the wire-cased one. The builder now checks and fills them with getHeaderRaw and setHeaderRaw. The Claude mimic debug line read the same raw-cased headers with Header.Get and logged empty values. It now reads them with getHeaderRaw. --- .../internal/service/gateway_count_tokens.go | 8 +- .../gateway_count_tokens_raw_headers_test.go | 87 +++++++++++++++++++ backend/internal/service/gateway_service.go | 2 +- 3 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 backend/internal/service/gateway_count_tokens_raw_headers_test.go diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index a6a493e25e..0f23f3379c 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -448,11 +448,11 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( // targetURL 的 base 取值),其余保持 extra/default 行为。 setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL) - if req.Header.Get("content-type") == "" { - req.Header.Set("content-type", "application/json") + if getHeaderRaw(req.Header, "content-type") == "" { + setHeaderRaw(req.Header, "content-type", "application/json") } - if req.Header.Get("anthropic-version") == "" { - req.Header.Set("anthropic-version", "2023-06-01") + if getHeaderRaw(req.Header, "anthropic-version") == "" { + setHeaderRaw(req.Header, "anthropic-version", "2023-06-01") } // 账号级请求头覆写(最终生效,覆盖上面所有来源的同名头) diff --git a/backend/internal/service/gateway_count_tokens_raw_headers_test.go b/backend/internal/service/gateway_count_tokens_raw_headers_test.go new file mode 100644 index 0000000000..04849c25a8 --- /dev/null +++ b/backend/internal/service/gateway_count_tokens_raw_headers_test.go @@ -0,0 +1,87 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func headerKeysFold(h http.Header, name string) []string { + var keys []string + for k := range h { + if strings.EqualFold(k, name) { + keys = append(keys, k) + } + } + return keys +} + +// The count_tokens passthrough builder copies client headers under their wire casing +// (lowercase content-type / anthropic-version). It must look those up under the same +// key before filling in defaults, so the upstream request carries exactly one of each. +func TestCountTokensPassthroughSendsOneContentTypeAndVersion(t *testing.T) { + tests := []struct { + name string + clientSends bool + wantType string + wantVersion string + }{ + {"client sent both", true, "application/json; charset=utf-8", "2024-01-01"}, + {"client sent neither", false, "application/json", "2023-06-01"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil) + if tt.clientSends { + c.Request.Header.Set("Anthropic-Version", tt.wantVersion) + c.Request.Header.Set("Content-Type", tt.wantType) + } + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key"}, + Status: StatusActive, + Schedulable: true, + } + svc := &GatewayService{cfg: &config.Config{}} + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}`) + + req, err := svc.buildCountTokensRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key") + require.NoError(t, err) + + require.Equal(t, []string{"content-type"}, headerKeysFold(req.Header, "content-type")) + require.Equal(t, []string{tt.wantType}, req.Header["content-type"]) + require.Equal(t, []string{"anthropic-version"}, headerKeysFold(req.Header, "anthropic-version")) + require.Equal(t, []string{tt.wantVersion}, req.Header["anthropic-version"]) + }) + } +} + +// The Claude mimic debug line must report headers stored under their wire casing. +func TestBuildClaudeMimicDebugLineReadsRawCasedHeaders(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "https://upstream.example/v1/messages", nil) + setHeaderRaw(req.Header, "anthropic-version", "2023-06-01") + setHeaderRaw(req.Header, "anthropic-beta", "beta-a") + setHeaderRaw(req.Header, "content-type", "application/json") + setHeaderRaw(req.Header, "x-app", "cli") + setHeaderRaw(req.Header, "X-Stainless-OS", "Linux") + + line := buildClaudeMimicDebugLine(req, []byte(`{}`), nil, "oauth", true) + + require.Contains(t, line, `anthropic-version="2023-06-01"`) + require.Contains(t, line, `anthropic-beta="beta-a"`) + require.Contains(t, line, `content-type="application/json"`) + require.Contains(t, line, `x-app="cli"`) + require.Contains(t, line, `x-stainless-os="Linux"`) +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..48e9a1b5de 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -350,7 +350,7 @@ func buildClaudeMimicDebugLine(req *http.Request, body []byte, account *Account, h := make([]string, 0, len(interesting)) for _, k := range interesting { - if v := req.Header.Get(k); v != "" { + if v := getHeaderRaw(req.Header, k); v != "" { h = append(h, fmt.Sprintf("%s=%q", k, safeHeaderValueForLog(k, v))) } } From 5854a1db43ad36f2c9c42e66f3dd1147a1bccff8 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:53:53 -0800 Subject: [PATCH 56/85] fix(upstream): detect dead upstream connections in about 30s Connections from newUpstreamDialer were dialed with net.Dialer{KeepAlive: 30s}. Go then keeps TCP_KEEPINTVL 15 s and TCP_KEEPCNT 9, so a peer that stops answering is declared dead 165 s after its last packet, and no TCP_USER_TIMEOUT is set. The dialer now sets KeepAliveConfig{Idle 15 s, Interval 5 s, Count 3} and, on Linux, TCP_USER_TIMEOUT 30 s (idle + interval x count) through Dialer.Control. Other platforms keep the keep-alive configuration only. SOCKS5 and TLS fingerprint transports keep their own dialers. --- backend/internal/repository/http_upstream.go | 12 ++- .../http_upstream_dial_timeout_test.go | 2 +- .../repository/http_upstream_keepalive.go | 23 ++++++ .../http_upstream_keepalive_linux.go | 21 ++++++ .../http_upstream_keepalive_linux_test.go | 73 +++++++++++++++++++ .../http_upstream_keepalive_other.go | 9 +++ 6 files changed, 135 insertions(+), 5 deletions(-) create mode 100644 backend/internal/repository/http_upstream_keepalive.go create mode 100644 backend/internal/repository/http_upstream_keepalive_linux.go create mode 100644 backend/internal/repository/http_upstream_keepalive_linux_test.go create mode 100644 backend/internal/repository/http_upstream_keepalive_other.go diff --git a/backend/internal/repository/http_upstream.go b/backend/internal/repository/http_upstream.go index e830b43380..af965e15ac 100644 --- a/backend/internal/repository/http_upstream.go +++ b/backend/internal/repository/http_upstream.go @@ -63,8 +63,6 @@ const ( // 上游域名被解析到 443 不可达的 IP 时(DNS 污染/路由异常),单个账号就要卡满 // 内核超时;而多账号故障转移是串行的,一次请求会阻塞数分钟且不写中间错误。 defaultUpstreamDialTimeout = 10 * time.Second - // defaultUpstreamDialKeepAlive: TCP keepalive 探测间隔,与 Go 默认值保持一致 - defaultUpstreamDialKeepAlive = 30 * time.Second // defaultUpstreamTLSHandshakeTimeout: TLS 握手超时(10秒) // 与建连超时同量级,避免 TCP 已连通但对端不推进握手时无限等待 defaultUpstreamTLSHandshakeTimeout = 10 * time.Second @@ -1365,8 +1363,14 @@ func defaultPoolSettings(cfg *config.Config) poolSettings { // 建连没有任何超时上限,只能等内核 TCP 重传耗尽(Linux 约 130 秒)。 func newUpstreamDialer() *net.Dialer { return &net.Dialer{ - Timeout: defaultUpstreamDialTimeout, - KeepAlive: defaultUpstreamDialKeepAlive, + Timeout: defaultUpstreamDialTimeout, + KeepAliveConfig: net.KeepAliveConfig{ + Enable: true, + Idle: upstreamKeepAliveIdle, + Interval: upstreamKeepAliveInterval, + Count: upstreamKeepAliveCount, + }, + Control: upstreamDialControl, } } diff --git a/backend/internal/repository/http_upstream_dial_timeout_test.go b/backend/internal/repository/http_upstream_dial_timeout_test.go index 00d6ce1a41..9660624f7b 100644 --- a/backend/internal/repository/http_upstream_dial_timeout_test.go +++ b/backend/internal/repository/http_upstream_dial_timeout_test.go @@ -30,7 +30,7 @@ func TestNewUpstreamDialerHasBoundedTimeout(t *testing.T) { require.Greater(t, dialer.Timeout, time.Duration(0), "建连超时必须有上限") require.Equal(t, defaultUpstreamDialTimeout, dialer.Timeout) - require.Equal(t, defaultUpstreamDialKeepAlive, dialer.KeepAlive) + require.Equal(t, net.KeepAliveConfig{Enable: true, Idle: 15 * time.Second, Interval: 5 * time.Second, Count: 3}, dialer.KeepAliveConfig) } // 建连超时对 HTTP 代理同样生效:Transport.Proxy 走的仍是 DialContext, diff --git a/backend/internal/repository/http_upstream_keepalive.go b/backend/internal/repository/http_upstream_keepalive.go new file mode 100644 index 0000000000..51fb8cb8c1 --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive.go @@ -0,0 +1,23 @@ +package repository + +import "time" + +// TCP keep-alive of upstream connections (newUpstreamDialer). A connection +// whose peer stops answering is aborted upstreamTCPUserTimeout after its last +// received packet: idle 15 s, then 3 probes 5 s apart. With the previous +// KeepAlive of 30 s and Go's default interval 15 s and count 9, the same case +// took 165 s. +// +// TCP_USER_TIMEOUT (Linux only, see upstreamDialControl) is set to +// idle + interval * count, as Cloudflare's "When TCP sockets refuse to die" +// (2019) recommends when both are used: once it is set the kernel aborts on it +// rather than on the probe count, so a larger value would add probes and a +// smaller one would cut them. It also bounds request data the peer never +// acknowledges, where keep-alive does not run. gRPC proposal A18 likewise sets +// it only on Linux. +const ( + upstreamKeepAliveIdle = 15 * time.Second + upstreamKeepAliveInterval = 5 * time.Second + upstreamKeepAliveCount = 3 + upstreamTCPUserTimeout = upstreamKeepAliveIdle + upstreamKeepAliveInterval*upstreamKeepAliveCount +) diff --git a/backend/internal/repository/http_upstream_keepalive_linux.go b/backend/internal/repository/http_upstream_keepalive_linux.go new file mode 100644 index 0000000000..607a3120cf --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive_linux.go @@ -0,0 +1,21 @@ +//go:build linux + +package repository + +import "syscall" + +// tcpUserTimeout is TCP_USER_TIMEOUT from Linux include/uapi/linux/tcp.h; the +// standard library's syscall package does not define it on linux/amd64. +const tcpUserTimeout = 0x12 + +// upstreamDialControl sets TCP_USER_TIMEOUT on each upstream socket +// before it connects. +func upstreamDialControl(_, _ string, raw syscall.RawConn) error { + var sockErr error + if err := raw.Control(func(fd uintptr) { + sockErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, tcpUserTimeout, int(upstreamTCPUserTimeout.Milliseconds())) + }); err != nil { + return err + } + return sockErr +} diff --git a/backend/internal/repository/http_upstream_keepalive_linux_test.go b/backend/internal/repository/http_upstream_keepalive_linux_test.go new file mode 100644 index 0000000000..ec1cfdf14d --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive_linux_test.go @@ -0,0 +1,73 @@ +//go:build linux + +package repository + +import ( + "context" + "net" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +// TCP_USER_TIMEOUT in Linux include/uapi/linux/tcp.h. +const testTCPUserTimeoutOpt = 0x12 + +// A socket dialed by the upstream dialer carries the keep-alive configuration +// and TCP_USER_TIMEOUT, read back from the kernel. +func TestUpstreamDialerSetsKeepAliveAndUserTimeoutOnTheSocket(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = listener.Close() }) + accepted := make(chan net.Conn, 1) + go func() { + server, err := listener.Accept() + if err != nil { + close(accepted) + return + } + accepted <- server + }() + + conn, err := newUpstreamDialer().DialContext(context.Background(), "tcp", listener.Addr().String()) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + if server, ok := <-accepted; ok { + t.Cleanup(func() { _ = server.Close() }) + } + tcpConn, ok := conn.(*net.TCPConn) + require.True(t, ok, "%T", conn) + raw, err := tcpConn.SyscallConn() + require.NoError(t, err) + + got := map[string]int{} + var readErr error + require.NoError(t, raw.Control(func(fd uintptr) { + for _, opt := range []struct { + name string + level, which int + }{ + {"SO_KEEPALIVE", syscall.SOL_SOCKET, syscall.SO_KEEPALIVE}, + {"TCP_KEEPIDLE", syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE}, + {"TCP_KEEPINTVL", syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL}, + {"TCP_KEEPCNT", syscall.IPPROTO_TCP, syscall.TCP_KEEPCNT}, + {"TCP_USER_TIMEOUT", syscall.IPPROTO_TCP, testTCPUserTimeoutOpt}, + } { + value, err := syscall.GetsockoptInt(int(fd), opt.level, opt.which) + if err != nil { + readErr = err + return + } + got[opt.name] = value + } + })) + require.NoError(t, readErr) + require.Equal(t, map[string]int{ + "SO_KEEPALIVE": 1, + "TCP_KEEPIDLE": 15, + "TCP_KEEPINTVL": 5, + "TCP_KEEPCNT": 3, + "TCP_USER_TIMEOUT": 30000, + }, got) +} diff --git a/backend/internal/repository/http_upstream_keepalive_other.go b/backend/internal/repository/http_upstream_keepalive_other.go new file mode 100644 index 0000000000..f7f61b2036 --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive_other.go @@ -0,0 +1,9 @@ +//go:build !linux + +package repository + +import "syscall" + +// upstreamDialControl is nil off Linux: TCP_USER_TIMEOUT is a Linux socket +// option, and the keep-alive configuration alone bounds idle connections. +var upstreamDialControl func(network, address string, c syscall.RawConn) error From 1f2242436293c1a64e5e17b17ca1033af902f232 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 01:49:10 -0800 Subject: [PATCH 57/85] fix(gateway): keep client metadata.user_id in Chat Completions to Anthropic ChatCompletionsRequest and ResponsesRequest have no metadata field and the conversion never sets AnthropicRequest.Metadata, so the user_id a client sends in metadata never reached the Anthropic request. withChatCompletionsMetadataUserID sets metadata.user_id on the converted body, byte for byte, when the client's top-level metadata.user_id is a string that ParseMetadataUserID accepts. Other metadata keys and ids that do not parse are not carried, and the body is unchanged in every other case. It is called right after the Anthropic body is marshaled in GatewayService.ForwardAsChatCompletions, for non-OAuth accounts only, and in OpenAIGatewayService.forwardChatCompletionsViaNativeAnthropic, which only serves API key accounts. OAuth accounts are unchanged: the mimicry already synthesizes their metadata.user_id. Fixes #8783 --- .../service/chat_completions_metadata.go | 32 +++ .../service/chat_completions_metadata_test.go | 192 ++++++++++++++++++ .../gateway_forward_as_chat_completions.go | 4 + ...teway_chat_completions_anthropic_native.go | 1 + 4 files changed, 229 insertions(+) create mode 100644 backend/internal/service/chat_completions_metadata.go create mode 100644 backend/internal/service/chat_completions_metadata_test.go diff --git a/backend/internal/service/chat_completions_metadata.go b/backend/internal/service/chat_completions_metadata.go new file mode 100644 index 0000000000..0eb94bfb23 --- /dev/null +++ b/backend/internal/service/chat_completions_metadata.go @@ -0,0 +1,32 @@ +package service + +import ( + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// withChatCompletionsMetadataUserID carries the client's top-level +// metadata.user_id of a Chat Completions request into the Anthropic body +// converted from it. ChatCompletionsRequest and ResponsesRequest have no +// metadata field, so the conversion never sets AnthropicRequest.Metadata and +// without this the Anthropic request never sees the id the client sent. +// +// Only a string user_id that ParseMetadataUserID accepts (JSON form with +// non-empty device_id and session_id, or the legacy form) is carried, as the +// raw JSON string token of the original body, so its bytes do not change. +// Every other metadata key is dropped. In every other case anthropicBody is +// returned as it is. +func withChatCompletionsMetadataUserID(chatBody, anthropicBody []byte) []byte { + userID := gjson.GetBytes(chatBody, "metadata.user_id") + if userID.Type != gjson.String { + return anthropicBody + } + if parsed := ParseMetadataUserID(userID.String()); parsed == nil || parsed.SessionID == "" { + return anthropicBody + } + out, err := sjson.SetRawBytes(anthropicBody, "metadata", []byte(`{"user_id":`+userID.Raw+`}`)) + if err != nil { + return anthropicBody + } + return out +} diff --git a/backend/internal/service/chat_completions_metadata_test.go b/backend/internal/service/chat_completions_metadata_test.go new file mode 100644 index 0000000000..2ad68da361 --- /dev/null +++ b/backend/internal/service/chat_completions_metadata_test.go @@ -0,0 +1,192 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const ( + chatMetaSessionID = "3f0c9a52-7b1e-4d6a-9c38-5e2f0a1b7c44" + chatMetaJSONUserID = `{"device_id":"device-1","session_id":"` + chatMetaSessionID + `"}` + chatMetaLegacyUser = "user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account__session_" + chatMetaSessionID + chatMetaConverted = `{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"stream":true}` + chatMetaChatPrefix = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],` + chatMetaNoMetaChat = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}` + chatMetaOnlyUserKey = `{"user_id":` +) + +func chatMetaQuote(t *testing.T, s string) string { + t.Helper() + b, err := json.Marshal(s) + require.NoError(t, err) + return string(b) +} + +func TestWithChatCompletionsMetadataUserID_Carries(t *testing.T) { + for name, userID := range map[string]string{"json": chatMetaJSONUserID, "legacy": chatMetaLegacyUser} { + t.Run(name, func(t *testing.T) { + quoted := chatMetaQuote(t, userID) + chat := []byte(chatMetaChatPrefix + `"metadata":{"user_id":` + quoted + `}}`) + out := withChatCompletionsMetadataUserID(chat, []byte(chatMetaConverted)) + + require.Equal(t, chatMetaOnlyUserKey+quoted+`}`, gjson.GetBytes(out, "metadata").Raw) + require.Equal(t, userID, gjson.GetBytes(out, "metadata.user_id").String()) + rest, err := sjson.DeleteBytes(out, "metadata") + require.NoError(t, err) + require.Equal(t, chatMetaConverted, string(rest), "everything but metadata is unchanged") + }) + } +} + +func TestWithChatCompletionsMetadataUserID_KeepsEscapesAndOtherKeysOut(t *testing.T) { + // The id is carried as the client's own string token, escapes included. + userID := `{"device_id":"dév","session_id":"` + chatMetaSessionID + `"}` + chat := []byte(chatMetaChatPrefix + `"metadata":{"trace":"x","user_id":"{\"device_id\":\"dév\",\"session_id\":\"` + chatMetaSessionID + `\"}","other":{"a":1}}}`) + out := withChatCompletionsMetadataUserID(chat, []byte(chatMetaConverted)) + require.Equal(t, `{"user_id":"{\"device_id\":\"dév\",\"session_id\":\"`+chatMetaSessionID+`\"}"}`, gjson.GetBytes(out, "metadata").Raw) + require.Equal(t, userID, gjson.GetBytes(out, "metadata.user_id").String()) + require.False(t, gjson.GetBytes(out, "metadata.trace").Exists()) + require.False(t, gjson.GetBytes(out, "metadata.other").Exists()) +} + +func TestWithChatCompletionsMetadataUserID_LeavesBodyAlone(t *testing.T) { + cases := map[string]string{ + "no metadata": chatMetaNoMetaChat, + "metadata string": chatMetaChatPrefix + `"metadata":"x"}`, + "metadata array": chatMetaChatPrefix + `"metadata":[{"user_id":` + chatMetaQuote(t, chatMetaJSONUserID) + `}]}`, + "metadata null": chatMetaChatPrefix + `"metadata":null}`, + "metadata without id": chatMetaChatPrefix + `"metadata":{"trace":"x"}}`, + "user_id number": chatMetaChatPrefix + `"metadata":{"user_id":12345}}`, + "user_id object": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaJSONUserID + `}}`, + "user_id array": chatMetaChatPrefix + `"metadata":{"user_id":[` + chatMetaQuote(t, chatMetaJSONUserID) + `]}}`, + "user_id null": chatMetaChatPrefix + `"metadata":{"user_id":null}}`, + "user_id empty": chatMetaChatPrefix + `"metadata":{"user_id":""}}`, + "user_id bare uuid": chatMetaChatPrefix + `"metadata":{"user_id":"` + chatMetaSessionID + `"}}`, + "user_id free text": chatMetaChatPrefix + `"metadata":{"user_id":"alice"}}`, + "json without device_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"session_id":"`+chatMetaSessionID+`"}`) + `}}`, + "json empty device_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"","session_id":"`+chatMetaSessionID+`"}`) + `}}`, + "json without session_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"device-1"}`) + `}}`, + "json empty session_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"device-1","session_id":""}`) + `}}`, + "json malformed": chatMetaChatPrefix + `"metadata":{"user_id":"{\"device_id\":"}}`, + "legacy short session": chatMetaChatPrefix + `"metadata":{"user_id":"user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account__session_123"}}`, + "top-level user only": chatMetaChatPrefix + `"user":` + chatMetaQuote(t, chatMetaJSONUserID) + `}`, + } + for name, chat := range cases { + t.Run(name, func(t *testing.T) { + out := withChatCompletionsMetadataUserID([]byte(chat), []byte(chatMetaConverted)) + require.Equal(t, chatMetaConverted, string(out)) + require.False(t, gjson.GetBytes(out, "metadata").Exists()) + }) + } +} + +func chatMetaStreamUpstream() *httpUpstreamRecorder { + return &httpUpstreamRecorder{resp: nativeAnthropicStreamResponse()} +} + +func chatMetaRequestBody(userID string) []byte { + return []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true,` + + `"metadata":{"trace":"x","user_id":` + userID + `}}`) +} + +func chatMetaContext(body []byte) *gin.Context { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + return c +} + +// The Anthropic-platform path (GatewayService.ForwardAsChatCompletions). +func TestForwardAsChatCompletions_CarriesMetadataUserID(t *testing.T) { + for name, tc := range map[string]struct { + userID string + want bool + }{ + "json": {chatMetaQuote(t, chatMetaJSONUserID), true}, + "legacy": {chatMetaQuote(t, chatMetaLegacyUser), true}, + "bare id": {chatMetaQuote(t, chatMetaSessionID), false}, + "number": {`12345`, false}, + } { + t.Run(name, func(t *testing.T) { + body := chatMetaRequestBody(tc.userID) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-test"}} + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + if !tc.want { + require.False(t, gjson.GetBytes(upstream.lastBody, "metadata").Exists(), string(upstream.lastBody)) + return + } + require.Equal(t, `{"user_id":`+tc.userID+`}`, gjson.GetBytes(upstream.lastBody, "metadata").Raw, string(upstream.lastBody)) + }) + } +} + +// OAuth accounts keep the id the mimicry synthesizes: the client's id is not carried. +func TestForwardAsChatCompletions_OAuthAccountKeepsSynthesizedMetadataUserID(t *testing.T) { + forward := func(t *testing.T, body []byte) []byte { + t.Helper() + upstream := chatMetaStreamUpstream() + svc := &GatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + identityService: NewIdentityService(&stubIdentityCache{fingerprint: &Fingerprint{ + UserAgent: "claude-cli/2.9.0 (external, cli)", ClientID: "test-client", UpdatedAt: time.Now().Unix(), + }}), + } + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "tok"}} + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + return upstream.lastBody + } + + withID := forward(t, chatMetaRequestBody(chatMetaQuote(t, chatMetaJSONUserID))) + withoutID := forward(t, []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true,"metadata":{"trace":"x"}}`)) + + require.NotEmpty(t, gjson.GetBytes(withoutID, "metadata.user_id").String(), string(withoutID)) + require.Equal(t, gjson.GetBytes(withoutID, "metadata").Raw, gjson.GetBytes(withID, "metadata").Raw, string(withID)) + require.NotContains(t, string(withID), "device-1") +} + +// The native Anthropic endpoint path (OpenAIGatewayService.forwardChatCompletionsViaNativeAnthropic). +func TestForwardChatCompletionsViaNativeAnthropic_CarriesMetadataUserID(t *testing.T) { + for name, tc := range map[string]struct { + userID string + want bool + }{ + "json": {chatMetaQuote(t, chatMetaJSONUserID), true}, + "legacy": {chatMetaQuote(t, chatMetaLegacyUser), true}, + "bare id": {chatMetaQuote(t, chatMetaSessionID), false}, + "number": {`12345`, false}, + } { + t.Run(name, func(t *testing.T) { + body := chatMetaRequestBody(tc.userID) + upstream := chatMetaStreamUpstream() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.forwardChatCompletionsViaNativeAnthropic(context.Background(), chatMetaContext(body), nativeAnthropicTestAccount(), body, "") + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + if !tc.want { + require.False(t, gjson.GetBytes(upstream.lastBody, "metadata").Exists(), string(upstream.lastBody)) + return + } + require.Equal(t, `{"user_id":`+tc.userID+`}`, gjson.GetBytes(upstream.lastBody, "metadata").Raw, string(upstream.lastBody)) + }) + } +} diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index a1f9786719..7eecec604e 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -94,6 +94,10 @@ func (s *GatewayService) ForwardAsChatCompletions( if err != nil { return nil, fmt.Errorf("marshal anthropic request: %w", err) } + if !account.IsOAuth() { + // OAuth accounts get their id from the mimicry below. + anthropicBody = withChatCompletionsMetadataUserID(body, anthropicBody) + } // 6. Apply Claude Code mimicry for OAuth accounts. // Chat Completions 协议进来的请求永远不是 Claude Code 客户端,所以对 OAuth 账号 diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 5c2d86b87d..04e5a4f9f5 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -93,6 +93,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( if err != nil { return nil, fmt.Errorf("marshal anthropic request: %w", err) } + anthropicBody = withChatCompletionsMetadataUserID(body, anthropicBody) // 与 /v1/messages 直通路径相同的 pre-filter。 anthropicBody = StripEmptyTextBlocks(anthropicBody) From aee71b85b9df233f914ddd6be46f51a2edd40f23 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:55:10 -0800 Subject: [PATCH 58/85] fix(gateway): restore public model in composite-routed responses When a composite route rewrites the request model to the route's upstream model, Messages responses reported the upstream model instead of the public model the client asked for. Restore the public name in streaming and non-streaming responses on the Anthropic forward path, the Anthropic API-key passthrough, and the Messages-to-OpenAI Responses and Chat Completions bridges. The Bedrock, Gemini and Antigravity paths and the native Anthropic relay on OpenAI gateway accounts are not covered here. Responses are unchanged when no route matched or the route did not rename the model. --- .../internal/service/composite_platform.go | 29 +++ .../composite_route_client_model_test.go | 220 ++++++++++++++++++ .../service/gateway_anthropic_passthrough.go | 8 + .../service/gateway_upstream_response.go | 10 + .../service/openai_gateway_messages.go | 4 +- .../openai_gateway_messages_chat_fallback.go | 4 +- 6 files changed, 271 insertions(+), 4 deletions(-) create mode 100644 backend/internal/service/composite_route_client_model_test.go diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index b7fcfd3451..ddaf2d83ad 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -6,6 +6,8 @@ import ( "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) // WithResolvedTargetPlatform stores the concrete provider chosen for a request @@ -73,6 +75,33 @@ func RequestedPublicModelFromContext(ctx context.Context) (string, bool) { return model, true } +// compositeClientModel returns the public model the client asked for when a +// composite route sent a different model upstream, and fallback otherwise. The +// response reports that public name whatever model the upstream says served it. +func compositeClientModel(ctx context.Context, fallback string) string { + publicModel, ok := RequestedPublicModelFromContext(ctx) + if !ok { + return fallback + } + if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); !ok || upstreamModel == publicModel { + return fallback + } + return publicModel +} + +// restoreCompositeClientModel reports the client's public model in an Anthropic +// response body when a composite route rewrote the model. +func restoreCompositeClientModel(ctx context.Context, body []byte) []byte { + clientModel := compositeClientModel(ctx, "") + if clientModel == "" || !gjson.GetBytes(body, "model").Exists() { + return body + } + if rewritten, err := sjson.SetBytes(body, "model", clientModel); err == nil { + return rewritten + } + return body +} + func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) { if ctx == nil { return "", false diff --git a/backend/internal/service/composite_route_client_model_test.go b/backend/internal/service/composite_route_client_model_test.go new file mode 100644 index 0000000000..cd3af8b80d --- /dev/null +++ b/backend/internal/service/composite_route_client_model_test.go @@ -0,0 +1,220 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// publicModelRoute serves requests for public-model with claude-opus-5-5. +func publicModelRoute() CompositeModelRoute { + return CompositeModelRoute{ + ID: 1, + GroupID: 11, + PublicModel: "public-model", + MatchType: CompositeRouteMatchExact, + TargetPlatform: PlatformAnthropic, + UpstreamModel: "claude-opus-5-5", + Endpoint: CompositeRouteEndpointAny, + Priority: 100, + Enabled: true, + } +} + +// routeCompositeBody resolves body's model against route and rewrites the +// model the way the composite middleware does before any handler runs. +func routeCompositeBody(t *testing.T, route CompositeModelRoute, endpoint string, body []byte) (context.Context, []byte) { + t.Helper() + resolver := NewCompositeRouteResolver(compositeRouteRepoStub{routes: []CompositeModelRoute{route}}) + decision, err := resolver.Resolve(context.Background(), route.GroupID, gjson.GetBytes(body, "model").String(), endpoint) + require.NoError(t, err) + require.True(t, decision.Matched) + body, err = sjson.SetBytes(body, "model", decision.UpstreamModel) + require.NoError(t, err) + return WithCompositeRouteDecision(context.Background(), decision), body +} + +func anthropicMessageStartModel(t *testing.T, sse string) string { + t.Helper() + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if ok && gjson.Get(data, "type").String() == "message_start" { + return gjson.Get(data, "message.model").String() + } + } + t.Fatalf("no message_start event in stream:\n%s", sse) + return "" +} + +func TestCompositeRouteRestoresPublicModelOnAnthropicForward(t *testing.T) { + gin.SetMode(gin.TestMode) + accounts := map[string]func() *Account{ + "oauth": newAnthropicOAuthAccountForPartialUsageTest, + "apikey-passthrough": newAnthropicAPIKeyAccountForTest, + } + for accountName, newAccount := range accounts { + for _, stream := range []bool{false, true} { + t.Run(accountName+"/stream="+strconv.FormatBool(stream), func(t *testing.T) { + client := []byte(`{"model":"public-model","max_tokens":16,"stream":` + strconv.FormatBool(stream) + + `,"messages":[{"role":"user","content":"hi"}]}`) + ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client) + + // The upstream reports its own dated id: the client still sees + // the public name it asked for. + upstreamBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[{"type":"text","text":"hi"}],"usage":{"input_tokens":1,"output_tokens":1}}` + contentType := "application/json" + if stream { + upstreamBody = strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`, + "", + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + "", + `event: message_stop`, + `data: {"type":"message_stop"}`, + "", + "", + }, "\n") + contentType = "text/event-stream" + } + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := newForwardPartialUsageServiceForTest(upstream) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + + _, err = svc.Forward(ctx, c, newAccount(), parsed) + require.NoError(t, err) + + require.Equal(t, "claude-opus-5-5", gjson.GetBytes(upstream.lastBody, "model").String()) + if stream { + require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String())) + } else { + require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String()) + require.Equal(t, "hi", gjson.GetBytes(rec.Body.Bytes(), "content.0.text").String()) + } + }) + } + } +} + +func TestCompositeRouteRestoresPublicModelOnResponsesBridge(t *testing.T) { + gin.SetMode(gin.TestMode) + route := publicModelRoute() + route.TargetPlatform = PlatformOpenAI + route.UpstreamModel = "gpt-5.6-sol" + for _, stream := range []bool{false, true} { + t.Run("stream="+strconv.FormatBool(stream), func(t *testing.T) { + client := []byte(`{"model":"public-model","max_tokens":16,"stream":` + strconv.FormatBool(stream) + + `,"messages":[{"role":"user","content":"hello"}]}`) + ctx, body := routeCompositeBody(t, route, CompositeRouteEndpointMessages, client) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_route", route.UpstreamModel)} + upstream.resp.Body = io.NopCloser(io.MultiReader( + strings.NewReader(`data: {"type":"response.created","response":{"id":"resp_route","model":"`+route.UpstreamModel+`"}}`+"\n\n"), + upstream.resp.Body, + )) + svc := &OpenAIGatewayService{httpUpstream: upstream, cfg: rawChatCompletionsTestConfig()} + + _, err := svc.ForwardAsAnthropic(ctx, c, rawGPT56ResponsesOAuthAccount(route.UpstreamModel, route.UpstreamModel), body, "", "") + require.NoError(t, err) + + require.Equal(t, route.UpstreamModel, gjson.GetBytes(upstream.lastBody, "model").String()) + if stream { + require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String())) + } else { + require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String()) + } + }) + } +} + +func TestCompositeRouteRestoresPublicModelOnChatCompletionsBridge(t *testing.T) { + gin.SetMode(gin.TestMode) + route := publicModelRoute() + route.TargetPlatform = PlatformOpenAI + route.UpstreamModel = "gpt-5.6-luna" + for _, stream := range []bool{false, true} { + t.Run("stream="+strconv.FormatBool(stream), func(t *testing.T) { + client := []byte(`{"model":"public-model","max_tokens":16,"messages":[{"role":"user","content":"hello"}],"stream":` + strconv.FormatBool(stream) + `}`) + ctx, body := routeCompositeBody(t, route, CompositeRouteEndpointMessages, client) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + upstreamBody := `{"id":"chatcmpl_route","object":"chat.completion","model":"gpt-5.6-luna","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}` + contentType := "application/json" + if stream { + upstreamBody = strings.Join([]string{ + `data: {"id":"chatcmpl_route","object":"chat.completion.chunk","model":"gpt-5.6-luna","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_route","object":"chat.completion.chunk","model":"gpt-5.6-luna","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`, + "", + "data: [DONE]", + "", + }, "\n") + contentType = "text/event-stream" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + account := forceChatMessagesFallbackAccount() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "") + require.NoError(t, err) + require.Equal(t, "gpt-5.6-luna", gjson.GetBytes(upstream.lastBody, "model").String()) + if stream { + require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String())) + } else { + require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String()) + } + }) + } +} + +func TestRestoreCompositeClientModelOnlyWhenRouteRewroteModel(t *testing.T) { + body := []byte(`{"id":"msg_1","type":"message","model":"claude-opus-5-5-20260901"}`) + route := publicModelRoute() + + renamedCtx, _ := routeCompositeBody(t, route, CompositeRouteEndpointMessages, []byte(`{"model":"public-model"}`)) + require.Equal(t, "public-model", gjson.GetBytes(restoreCompositeClientModel(renamedCtx, body), "model").String()) + require.Equal(t, "public-model", compositeClientModel(renamedCtx, "claude-opus-5-5")) + + route.PublicModel = route.UpstreamModel + sameCtx, _ := routeCompositeBody(t, route, CompositeRouteEndpointMessages, []byte(`{"model":"claude-opus-5-5"}`)) + require.Equal(t, string(body), string(restoreCompositeClientModel(sameCtx, body))) + require.Equal(t, "claude-opus-5-5", compositeClientModel(sameCtx, "claude-opus-5-5")) + + require.Equal(t, string(body), string(restoreCompositeClientModel(context.Background(), body))) + require.Equal(t, "claude-opus-5-5", compositeClientModel(context.Background(), "claude-opus-5-5")) + + noModel := []byte(`{"type":"error"}`) + require.Equal(t, string(noModel), string(restoreCompositeClientModel(renamedCtx, noModel))) +} diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index e7c99cb076..59bb98ad36 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -501,6 +501,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( keepaliveTimer.Reset(keepaliveInterval) } inPartialEvent := false + clientModel := compositeClientModel(ctx, "") for { select { @@ -560,6 +561,12 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } } + if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" { + if rewritten, err := sjson.Set(data, "message.model", clientModel); err == nil { + line = "data: " + rewritten + } + } + if !clientDisconnected { restored := string(reverseToolNamesIfPresent(c, []byte(line))) if _, err := io.WriteString(w, restored); err != nil { @@ -894,6 +901,7 @@ func (s *GatewayService) handleNonStreamingResponseAnthropicAPIKeyPassthrough( if contentType == "" { contentType = "application/json" } + body = restoreCompositeClientModel(ctx, body) body = reverseToolNamesIfPresent(c, body) c.Data(resp.StatusCode, contentType, body) return usage, nil diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 85b415e5cf..8f360756c9 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -856,6 +856,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } needModelReplace := originalModel != mappedModel + clientModel := compositeClientModel(ctx, "") clientDisconnected := false // 客户端断开标志,断开后继续读取上游以获取完整usage sawTerminalEvent := false useNoopDeltaKeepalive := c != nil && c.Request != nil && shouldUseClaudeCodeNoopDeltaKeepalive(c.GetHeader("User-Agent")) @@ -992,6 +993,14 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } } } + if clientModel != "" { + if msg, ok := event["message"].(map[string]any); ok { + if _, ok := msg["model"].(string); ok { + msg["model"] = clientModel + eventChanged = true + } + } + } usagePatch := s.extractSSEUsagePatch(event) if anthropicStreamEventIsTerminal(eventName, dataLine) { @@ -1466,6 +1475,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h if originalModel != mappedModel { body = s.replaceModelInResponseBody(body, mappedModel, originalModel) } + body = restoreCompositeClientModel(ctx, body) responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..7de3411799 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -679,7 +679,7 @@ func (s *OpenAIGatewayService) handleAnthropicBufferedStreamingResponse( // accumulated delta events so the client receives the full content. acc.SupplementResponseOutput(finalResponse) - anthropicResp := apicompat.ResponsesToAnthropic(finalResponse, originalModel) + anthropicResp := apicompat.ResponsesToAnthropic(finalResponse, compositeClientModel(c.Request.Context(), originalModel)) if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) @@ -1019,7 +1019,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( writeStreamHeaders := s.newStreamHeaderWriter(c, resp.Header) state := apicompat.NewResponsesEventToAnthropicState() - state.Model = originalModel + state.Model = compositeClientModel(c.Request.Context(), originalModel) var usage OpenAIUsage responseID := "" var firstTokenMs *int diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index 0a92e5963a..9dde1c88ba 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -170,7 +170,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( if err != nil { return nil, err } - anthropicResp := apicompat.ChatCompletionsResponseToAnthropic(ccResp, originalModel) + anthropicResp := apicompat.ChatCompletionsResponseToAnthropic(ccResp, compositeClientModel(c.Request.Context(), originalModel)) if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) @@ -205,7 +205,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( requestID := resp.Header.Get("x-request-id") writeStreamHeaders := s.newStreamHeaderWriter(c, resp.Header) - anthropicState := apicompat.NewChatCompletionsToAnthropicStreamState(originalModel) + anthropicState := apicompat.NewChatCompletionsToAnthropicStreamState(compositeClientModel(c.Request.Context(), originalModel)) clientDisconnected := false // 与 responses 兄弟不同:客户端断开后仍继续做事件转换(喂 anthropicState), From d05e8ef033db09bef1c77fe579801591322bc7cb Mon Sep 17 00:00:00 2001 From: feeeei Date: Sat, 14 Nov 2026 21:17:53 +0800 Subject: [PATCH 59/85] =?UTF-8?q?fix(usage):=20=E6=8C=89=E8=B4=A6=E6=88=B7?= =?UTF-8?q?=E7=AD=9B=E9=80=89=E6=97=B6=E6=A8=A1=E5=9E=8B=E4=B8=8E=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E5=88=86=E5=B8=83=E7=9A=84=E5=AE=9E=E9=99=85=E6=89=A3?= =?UTF-8?q?=E8=B4=B9=E4=B8=8D=E5=86=8D=E6=9B=BF=E6=8D=A2=E4=B8=BA=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E6=88=90=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模型统计和端点统计在仅按 account_id 过滤(无 user_id/api_key_id)时, 把 actual_cost 换成了账号成本 SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1));展开后的用户明细与分组分布用的是 真实 SUM(actual_cost),于是模型行「实际」会小于其下单个用户行的「实际」, 且与同页「成本」列数值相同。 - actual_cost 统一为用户实际扣费,账号成本由 account_cost 承载; EndpointStat 新增 account_cost,端点分布表增加「成本」列,用户侧 /api/v1/usage/stats 清零该字段、用户页隐藏该列 - Gemini 配额用量(geminiAggregateUsage、GetGeminiUsageTotalsBatch) 显式按账号成本累计,账号用量窗口展示不变 接口口径变化:仅按账户过滤时,/admin/dashboard/models、/admin/usage/stats 的 endpoints/upstream_endpoints/endpoint_paths、/admin/accounts/:id/stats 的 models/endpoints 中 actual_cost 由账号成本改为用户实际扣费,账号成本改看 account_cost;/admin/accounts/:id/stats 的 history/summary 口径不变。 --- backend/internal/handler/usage_handler.go | 3 ++ .../pkg/usagestats/usage_log_types.go | 5 ++- .../usage_log_repo_integration_test.go | 26 +++++++---- .../usage_log_repo_request_type_test.go | 45 +++++++++++++++++++ .../repository/usage_log_repo_stats.go | 27 ++++------- .../repository/usage_log_repo_trend.go | 12 ++--- backend/internal/service/gemini_quota.go | 4 +- backend/internal/service/gemini_quota_test.go | 12 +++++ .../charts/EndpointDistributionChart.vue | 11 ++++- frontend/src/types/index.ts | 5 ++- frontend/src/views/user/UsageView.vue | 1 + 11 files changed, 107 insertions(+), 44 deletions(-) diff --git a/backend/internal/handler/usage_handler.go b/backend/internal/handler/usage_handler.go index 987092ca46..eb212679cc 100644 --- a/backend/internal/handler/usage_handler.go +++ b/backend/internal/handler/usage_handler.go @@ -417,6 +417,9 @@ func (h *UsageHandler) Stats(c *gin.Context) { return } stats.TotalAccountCost = nil + for i := range stats.Endpoints { + stats.Endpoints[i].AccountCost = 0 + } stats.UpstreamEndpoints = nil stats.EndpointPaths = nil diff --git a/backend/internal/pkg/usagestats/usage_log_types.go b/backend/internal/pkg/usagestats/usage_log_types.go index 9d651d85a0..9b9c4cb668 100644 --- a/backend/internal/pkg/usagestats/usage_log_types.go +++ b/backend/internal/pkg/usagestats/usage_log_types.go @@ -111,8 +111,9 @@ type EndpointStat struct { Endpoint string `json:"endpoint"` Requests int64 `json:"requests"` TotalTokens int64 `json:"total_tokens"` - Cost float64 `json:"cost"` // 标准计费 - ActualCost float64 `json:"actual_cost"` // 实际扣除 + Cost float64 `json:"cost"` // 标准计费 + ActualCost float64 `json:"actual_cost"` // 实际扣除 + AccountCost float64 `json:"account_cost,omitempty"` // 账号成本(仅管理员接口返回) } // GroupUsageSummary represents today's, yesterday's, and cumulative cost for a single group. diff --git a/backend/internal/repository/usage_log_repo_integration_test.go b/backend/internal/repository/usage_log_repo_integration_test.go index 1ba7609fa4..ee0e9fcd85 100644 --- a/backend/internal/repository/usage_log_repo_integration_test.go +++ b/backend/internal/repository/usage_log_repo_integration_test.go @@ -1449,16 +1449,18 @@ func (s *UsageLogRepoSuite) TestGetModelStatsWithFilters() { base := time.Date(2025, 1, 15, 12, 0, 0, 0, time.UTC) + accountRate := 0.4 log1 := &service.UsageLog{ - UserID: user.ID, - APIKeyID: apiKey.ID, - AccountID: account.ID, - Model: "claude-3-opus", - InputTokens: 100, - OutputTokens: 200, - TotalCost: 0.5, - ActualCost: 0.5, - CreatedAt: base, + UserID: user.ID, + APIKeyID: apiKey.ID, + AccountID: account.ID, + Model: "claude-3-opus", + InputTokens: 100, + OutputTokens: 200, + TotalCost: 0.5, + ActualCost: 1.0, + AccountRateMultiplier: &accountRate, + CreatedAt: base, } _, err := s.repo.Create(s.ctx, log1) s.Require().NoError(err) @@ -1494,6 +1496,12 @@ func (s *UsageLogRepoSuite) TestGetModelStatsWithFilters() { stats, err = s.repo.GetModelStatsWithFilters(s.ctx, startTime, endTime, 0, 0, account.ID, 0, nil, nil, nil) s.Require().NoError(err, "GetModelStatsWithFilters account filter") s.Require().Len(stats, 2) + for _, stat := range stats { + if stat.Model == "claude-3-opus" { + s.Require().InEpsilon(1.0, stat.ActualCost, 0.0001) + s.Require().InEpsilon(0.2, stat.AccountCost, 0.0001) + } + } } // --- GetAccountUsageStats --- diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index c8fb2f62ad..b37a316857 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -1187,3 +1187,48 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { }) } + +func TestUsageLogRepositoryGetModelStatsAccountFilterKeepsActualCost(t *testing.T) { + db, mock := newSQLMock(t) + repo := &usageLogRepository{sql: db} + + start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) + end := start.Add(24 * time.Hour) + accountID := int64(42) + + mock.ExpectQuery("COALESCE\\(SUM\\(actual_cost\\), 0\\) as actual_cost,\\s+COALESCE\\(SUM\\(COALESCE\\(account_stats_cost, total_cost\\) \\* COALESCE\\(account_rate_multiplier, 1\\)\\), 0\\) as account_cost"). + WithArgs(start, end, accountID). + WillReturnRows(sqlmock.NewRows([]string{ + "model", "requests", "input_tokens", "output_tokens", + "cache_creation_tokens", "cache_read_tokens", "total_tokens", + "cost", "actual_cost", "account_cost", + }).AddRow("gemini-4-argon", int64(3), int64(10), int64(20), int64(0), int64(0), int64(30), 6.0, 2.4, 0.9)) + + results, err := repo.GetModelStatsWithUsageFiltersBySource(context.Background(), start, end, usagestats.UsageLogFilters{AccountID: accountID}, usagestats.ModelSourceRequested) + require.NoError(t, err) + require.Len(t, results, 1) + require.Equal(t, 2.4, results[0].ActualCost) + require.Equal(t, 0.9, results[0].AccountCost) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestUsageLogRepositoryGetEndpointStatsAccountFilterKeepsActualCost(t *testing.T) { + db, mock := newSQLMock(t) + repo := &usageLogRepository{sql: db} + + start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) + end := start.Add(24 * time.Hour) + accountID := int64(42) + + mock.ExpectQuery("COALESCE\\(SUM\\(actual_cost\\), 0\\) as actual_cost,\\s+COALESCE\\(SUM\\(COALESCE\\(account_stats_cost, total_cost\\) \\* COALESCE\\(account_rate_multiplier, 1\\)\\), 0\\) as account_cost"). + WithArgs(start, end, accountID). + WillReturnRows(sqlmock.NewRows([]string{"endpoint", "requests", "total_tokens", "cost", "actual_cost", "account_cost"}). + AddRow("/v1beta/models", int64(3), int64(30), 6.0, 2.4, 0.9)) + + results, err := repo.GetEndpointStatsWithFilters(context.Background(), start, end, 0, 0, accountID, 0, "", nil, nil, nil) + require.NoError(t, err) + require.Len(t, results, 1) + require.Equal(t, 2.4, results[0].ActualCost) + require.Equal(t, 0.9, results[0].AccountCost) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/repository/usage_log_repo_stats.go b/backend/internal/repository/usage_log_repo_stats.go index 91e0eaf77b..5dfb74646f 100644 --- a/backend/internal/repository/usage_log_repo_stats.go +++ b/backend/internal/repository/usage_log_repo_stats.go @@ -402,8 +402,8 @@ func (r *usageLogRepository) GetGeminiUsageTotalsBatch(ctx context.Context, acco COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE 1 END), 0) AS pro_requests, COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN (input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens) ELSE 0 END), 0) AS flash_tokens, COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE (input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens) END), 0) AS pro_tokens, - COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN actual_cost ELSE 0 END), 0) AS flash_cost, - COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE actual_cost END), 0) AS pro_cost + COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1) ELSE 0 END), 0) AS flash_cost, + COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1) END), 0) AS pro_cost FROM usage_logs WHERE account_id = ANY($1) AND created_at >= $2 AND created_at < $3 GROUP BY account_id @@ -736,7 +736,6 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us stats := &UsageStats{} var totalAccountCost float64 - useAccountCostForEndpoint := filters.AccountID > 0 && filters.UserID == 0 && filters.APIKeyID == 0 rows, err := r.sql.QueryContext(ctx, query, args...) if err != nil { return nil, err @@ -769,10 +768,6 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us } totalTokens := inputTokens + outputTokens + cacheCreationTokens + cacheReads - endpointActualCost := actualCost - if useAccountCostForEndpoint { - endpointActualCost = accountCost - } switch { case inboundGrouped == 1 && upstreamGrouped == 1: @@ -789,17 +784,17 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us case inboundGrouped == 0 && upstreamGrouped == 1: stats.Endpoints = append(stats.Endpoints, EndpointStat{ Endpoint: inboundEndpoint.String, Requests: requests, TotalTokens: totalTokens, - Cost: cost, ActualCost: endpointActualCost, + Cost: cost, ActualCost: actualCost, AccountCost: accountCost, }) case inboundGrouped == 1 && upstreamGrouped == 0: stats.UpstreamEndpoints = append(stats.UpstreamEndpoints, EndpointStat{ Endpoint: upstreamEndpoint.String, Requests: requests, TotalTokens: totalTokens, - Cost: cost, ActualCost: endpointActualCost, + Cost: cost, ActualCost: actualCost, AccountCost: accountCost, }) case inboundGrouped == 0 && upstreamGrouped == 0: stats.EndpointPaths = append(stats.EndpointPaths, EndpointStat{ Endpoint: inboundEndpoint.String + " -> " + upstreamEndpoint.String, - Requests: requests, TotalTokens: totalTokens, Cost: cost, ActualCost: endpointActualCost, + Requests: requests, TotalTokens: totalTokens, Cost: cost, ActualCost: actualCost, AccountCost: accountCost, }) } } @@ -838,21 +833,17 @@ type AccountUsageStatsResponse = usagestats.AccountUsageStatsResponse type EndpointStat = usagestats.EndpointStat func (r *usageLogRepository) getEndpointStatsByColumnWithFilters(ctx context.Context, endpointColumn string, startTime, endTime time.Time, userID, apiKeyID, accountID, groupID int64, model string, modelSource string, requestType *int16, stream *bool, billingType *int8, billingMode string) (results []EndpointStat, err error) { - actualCostExpr := "COALESCE(SUM(actual_cost), 0) as actual_cost" - if accountID > 0 && userID == 0 && apiKeyID == 0 { - actualCostExpr = "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost" - } - query := fmt.Sprintf(` SELECT COALESCE(NULLIF(TRIM(%s), ''), 'unknown') AS endpoint, COUNT(*) AS requests, COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) AS total_tokens, COALESCE(SUM(total_cost), 0) as cost, - %s + COALESCE(SUM(actual_cost), 0) as actual_cost, + COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost FROM usage_logs WHERE created_at >= $1 AND created_at < $2 - `, endpointColumn, actualCostExpr) + `, endpointColumn) args := []any{startTime, endTime} if userID > 0 { @@ -894,7 +885,7 @@ func (r *usageLogRepository) getEndpointStatsByColumnWithFilters(ctx context.Con results = make([]EndpointStat, 0) for rows.Next() { var row EndpointStat - if err := rows.Scan(&row.Endpoint, &row.Requests, &row.TotalTokens, &row.Cost, &row.ActualCost); err != nil { + if err := rows.Scan(&row.Endpoint, &row.Requests, &row.TotalTokens, &row.Cost, &row.ActualCost, &row.AccountCost); err != nil { return nil, err } results = append(results, row) diff --git a/backend/internal/repository/usage_log_repo_trend.go b/backend/internal/repository/usage_log_repo_trend.go index cc7a46ffbf..dcc706115e 100644 --- a/backend/internal/repository/usage_log_repo_trend.go +++ b/backend/internal/repository/usage_log_repo_trend.go @@ -449,12 +449,6 @@ func (r *usageLogRepository) GetModelStatsWithUsageFiltersBySource(ctx context.C } func (r *usageLogRepository) getModelStatsWithFiltersBySource(ctx context.Context, startTime, endTime time.Time, userID, apiKeyID, accountID, groupID int64, model string, requestType *int16, stream *bool, billingType *int8, source string, billingMode string, upstreamModelMismatch *bool, nativeCompactionV2 *bool) (results []ModelStat, err error) { - actualCostExpr := "COALESCE(SUM(actual_cost), 0) as actual_cost" - // 当仅按 account_id 聚合时,实际费用使用账号倍率(total_cost * account_rate_multiplier)。 - if accountID > 0 && userID == 0 && apiKeyID == 0 { - actualCostExpr = "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost" - } - accountCostExpr := "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost" modelExpr := resolveModelDimensionExpression(source) query := fmt.Sprintf(` @@ -467,11 +461,11 @@ func (r *usageLogRepository) getModelStatsWithFiltersBySource(ctx context.Contex COALESCE(SUM(cache_read_tokens), 0) as cache_read_tokens, COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) as total_tokens, COALESCE(SUM(total_cost), 0) as cost, - %s, - %s + COALESCE(SUM(actual_cost), 0) as actual_cost, + COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost FROM usage_logs WHERE created_at >= $1 AND created_at < $2 - `, modelExpr, actualCostExpr, accountCostExpr) + `, modelExpr) args := []any{startTime, endTime} if userID > 0 { diff --git a/backend/internal/service/gemini_quota.go b/backend/internal/service/gemini_quota.go index be927754cf..afe486998d 100644 --- a/backend/internal/service/gemini_quota.go +++ b/backend/internal/service/gemini_quota.go @@ -416,11 +416,11 @@ func geminiAggregateUsage(stats []usagestats.ModelStat) GeminiUsageTotals { case geminiModelFlash: totals.FlashRequests += stat.Requests totals.FlashTokens += stat.TotalTokens - totals.FlashCost += stat.ActualCost + totals.FlashCost += stat.AccountCost default: totals.ProRequests += stat.Requests totals.ProTokens += stat.TotalTokens - totals.ProCost += stat.ActualCost + totals.ProCost += stat.AccountCost } } return totals diff --git a/backend/internal/service/gemini_quota_test.go b/backend/internal/service/gemini_quota_test.go index 36e60f291e..69df88ea12 100644 --- a/backend/internal/service/gemini_quota_test.go +++ b/backend/internal/service/gemini_quota_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" "github.com/stretchr/testify/require" ) @@ -78,3 +79,14 @@ func geminiQuotaAPIKeyAccount(baseURL string) *Account { } return &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: credentials} } + +func TestGeminiAggregateUsageUsesAccountCost(t *testing.T) { + totals := geminiAggregateUsage([]usagestats.ModelStat{ + {Model: "gemini-3.7-flash", Requests: 2, TotalTokens: 20, ActualCost: 5, AccountCost: 1.5}, + {Model: "gemini-4-argon", Requests: 1, TotalTokens: 10, ActualCost: 8, AccountCost: 3}, + }) + require.Equal(t, int64(2), totals.FlashRequests) + require.Equal(t, 1.5, totals.FlashCost) + require.Equal(t, int64(1), totals.ProRequests) + require.Equal(t, 3.0, totals.ProCost) +} diff --git a/frontend/src/components/charts/EndpointDistributionChart.vue b/frontend/src/components/charts/EndpointDistributionChart.vue index a813df19b5..2cfc7f3110 100644 --- a/frontend/src/components/charts/EndpointDistributionChart.vue +++ b/frontend/src/components/charts/EndpointDistributionChart.vue @@ -83,6 +83,7 @@ {{ t('admin.dashboard.requests') }} {{ t('admin.dashboard.tokens') }} {{ t('admin.dashboard.actual') }} + {{ t('admin.dashboard.accountCost') }} {{ t('admin.dashboard.standard') }} @@ -109,15 +110,19 @@ ${{ formatCost(item.actual_cost) }} + + ${{ formatCost(item.account_cost ?? 0) }} + ${{ formatCost(item.cost) }} - + @@ -161,6 +166,7 @@ const props = withDefaults( showMetricToggle?: boolean showSourceToggle?: boolean enableBreakdown?: boolean + showAccountCost?: boolean startDate?: string endDate?: string filters?: Record @@ -174,7 +180,8 @@ const props = withDefaults( source: 'inbound', showMetricToggle: false, showSourceToggle: false, - enableBreakdown: true + enableBreakdown: true, + showAccountCost: true } ) diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 1d3fd163d4..f98a4b83a8 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -2089,8 +2089,9 @@ export interface EndpointStat { endpoint: string requests: number total_tokens: number - cost: number - actual_cost: number + cost: number // 标准计费 + actual_cost: number // 实际扣除 + account_cost?: number // 账号成本(仅管理员接口返回) } export interface GroupStat { diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index 8ced361457..688bc19817 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -58,6 +58,7 @@ :show-source-toggle="false" :show-metric-toggle="true" :enable-breakdown="false" + :show-account-cost="false" :title="t('usage.endpointDistribution')" :start-date="startDate" :end-date="endDate" From 82cd13d1ec23420563a72a011ec94a98be5e7a63 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Sat, 14 Nov 2026 21:28:25 +0800 Subject: [PATCH 60/85] fix(openai): fall back to memory when first-output spool creation fails --- .../service/openai_first_output_timeout.go | 5 +- .../openai_first_output_timeout_test.go | 79 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/openai_first_output_timeout.go b/backend/internal/service/openai_first_output_timeout.go index 3b47fdd7d4..438ec17f4d 100644 --- a/backend/internal/service/openai_first_output_timeout.go +++ b/backend/internal/service/openai_first_output_timeout.go @@ -145,7 +145,10 @@ func (s *openAIFirstOutputStage) prepareWrite(incoming int) error { } file, err := s.createTemp() if err != nil { - return fmt.Errorf("create first-output spool: %w", err) + // Unavailable temporary storage must not fail an otherwise valid stream. + // Keep buffering in memory under the same stage limit. + s.memoryOnly = true + return nil } path := file.Name() // Unlink before writing any request data. Unix keeps the file descriptor diff --git a/backend/internal/service/openai_first_output_timeout_test.go b/backend/internal/service/openai_first_output_timeout_test.go index ebab68c019..b1d392ad73 100644 --- a/backend/internal/service/openai_first_output_timeout_test.go +++ b/backend/internal/service/openai_first_output_timeout_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "os" + "path/filepath" "runtime" "strings" "sync" @@ -284,6 +285,84 @@ func TestOpenAIFirstOutputStageCommitCopiesSpoolAndRemovesTemp(t *testing.T) { require.NoError(t, stage.Close()) } +func TestOpenAIFirstOutputStageCreateFailurePreservesBoundedBuffer(t *testing.T) { + for _, useWriteString := range []bool{false, true} { + t.Run(fmt.Sprintf("write_string_%t", useWriteString), func(t *testing.T) { + stage := newOpenAIFirstOutputStage(70 * 1024) + stage.memoryOnly = false + t.Cleanup(func() { require.NoError(t, stage.Close()) }) + createCalls := 0 + stage.createTemp = func() (*os.File, error) { + createCalls++ + return nil, &os.PathError{Op: "open", Path: "unwritable/spool", Err: os.ErrPermission} + } + stage.removeFile = func(string) error { + t.Fatal("failed creation must not leave a spool to remove") + return nil + } + write := func(value string) (int, error) { + if useWriteString { + return stage.WriteString(value) + } + return stage.Write([]byte(value)) + } + + payload := "" + for _, chunk := range []string{strings.Repeat("a", 32*1024), strings.Repeat("b", 36*1024), strings.Repeat("c", 2*1024)} { + n, err := write(chunk) + require.NoError(t, err) + require.Equal(t, len(chunk), n) + payload += chunk + } + require.Equal(t, 1, createCalls, "fallback must not retry CreateTemp on later writes") + require.EqualValues(t, len(payload), stage.Buffered()) + + n, err := write("overflow") + require.Zero(t, n) + require.ErrorIs(t, err, errOpenAIFirstOutputStageLimit) + require.EqualValues(t, len(payload), stage.Buffered()) + var downstream bytes.Buffer + require.NoError(t, stage.CommitTo(&downstream)) + require.Equal(t, payload, downstream.String()) + require.Zero(t, stage.Buffered()) + }) + } +} + +func TestOpenAINativeFirstOutputWithUnavailableTempDir(t *testing.T) { + missingDir := filepath.Join(t.TempDir(), "missing") + for _, name := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(name, missingDir) + } + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + // Cross the disk-spill threshold before any semantic output is available. + preamble := `data: {"type":"response.created","response":{"id":"resp_no_temp","created_at":1700000000,"padding":"` + strings.Repeat("x", 68*1024) + `"}}` + "\n\n" + delta := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hello\"}\n\n" + payload := preamble + delta + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_no_temp\",\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\n\n" + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "X-Request-Id": []string{"request-no-temp"}, + }, Body: io.NopCloser(strings.NewReader(payload))} + + result, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.firstTokenMs) + require.True(t, strings.HasPrefix(rec.Body.String(), preamble+delta), "buffered preamble and first output must be forwarded intact") + require.Contains(t, rec.Body.String(), `"type":"response.completed"`) + require.Equal(t, 3, result.usage.InputTokens) + require.Equal(t, 2, result.usage.OutputTokens) + require.Equal(t, "request-no-temp", rec.Header().Get("X-Request-Id")) +} + func TestOpenAIFirstOutputStageUnlinkFailurePermanentlyFallsBackToMemoryAndRetriesCleanup(t *testing.T) { stage := newDefaultOpenAIFirstOutputStage() stage.memoryOnly = false From 38eb97bd7a2ac4635e0ba5e38a963b49554efa58 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 02:54:06 -0800 Subject: [PATCH 61/85] fix(openai): fail over Messages bridge errors before first content The Messages bridge wrote message_start as soon as upstream sent response.created, and a keepalive ping after one silent keepalive interval also counted as output, so the failover branches for failed frames, error frames and a missing terminal event could never run on a real stream and the error went to the client. The prelude is now held until the first content_block_delta, a terminal event or a failure. No change to which errors fail over: read errors still do not, and failures that do not fail over release the held prelude so the client sees the same bytes as before. Keepalive pings still flow while held and are counted as keepalive bytes, so the handler compares the written size net of them and writes later errors as SSE events. A cancelled request context while the prelude is held counts as a client disconnect, not an upstream failure. --- .../handler/openai_gateway_handler.go | 9 +- ...eway_messages_pre_content_failover_test.go | 141 +++++++++++++++ .../service/openai_compat_model_test.go | 5 +- .../service/openai_gateway_messages.go | 86 ++++++--- ...penai_gateway_messages_pre_content_test.go | 165 ++++++++++++++++++ 5 files changed, 383 insertions(+), 23 deletions(-) create mode 100644 backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go create mode 100644 backend/internal/service/openai_gateway_messages_pre_content_test.go diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index f70bce78b2..d2413ae82a 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1413,7 +1413,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { defaultMappedModel := strings.TrimSpace(effectiveMappedModel) // 应用渠道模型映射到请求体 forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel) - writerSizeBeforeForward := c.Writer.Size() + writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c) result, err := func() (*service.OpenAIForwardResult, error) { defer func() { if accountReleaseFunc != nil { @@ -1501,11 +1501,16 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { ) return } - if c.Writer.Size() != writerSizeBeforeForward { + if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) { h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err) h.handleAnthropicFailoverExhausted(c, failoverErr, true) return } + // Only keepalive bytes were written, so failover may continue, but + // every later error must be written as an SSE event. + if c.Writer.Written() { + streamStarted = true + } if failoverErr.ShouldReportAccountScheduleFailure() { h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err) } diff --git a/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go b/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go new file mode 100644 index 0000000000..6db9679fb6 --- /dev/null +++ b/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go @@ -0,0 +1,141 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + preContentHandlerCreated = `data: {"type":"response.created","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n" + preContentHandlerFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n" + preContentHandlerSuccess = preContentHandlerCreated + + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}` + "\n\n" + + `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer from second account"}` + "\n\n" + + `data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n" +) + +// preContentFailoverUpstream answers the first request with a stream that stalls +// past one keepalive tick and then fails before any content; later requests +// complete normally. +type preContentFailoverUpstream struct { + service.HTTPUpstream + mu sync.Mutex + hits []int64 +} + +func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + u.mu.Lock() + u.hits = append(u.hits, accountID) + first := len(u.hits) == 1 + u.mu.Unlock() + header := http.Header{"Content-Type": []string{"text/event-stream"}} + if !first { + return &http.Response{StatusCode: http.StatusOK, Header: header, Body: io.NopCloser(strings.NewReader(preContentHandlerSuccess))}, nil + } + pr, pw := io.Pipe() + go func() { + _, _ = io.WriteString(pw, preContentHandlerCreated) + time.Sleep(1300 * time.Millisecond) + _, _ = io.WriteString(pw, preContentHandlerFailed) + _ = pw.Close() + }() + return &http.Response{StatusCode: http.StatusOK, Header: header, Body: pr}, nil +} + +func (u *preContentFailoverUpstream) calls() int { + u.mu.Lock() + defer u.mu.Unlock() + return len(u.hits) +} + +func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) { + t.Helper() + gin.SetMode(gin.TestMode) + groupID := int64(9101) + accounts := make([]service.Account, 0, accountCount) + for i := 0; i < accountCount; i++ { + accounts = append(accounts, service.Account{ + ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"}, + }) + } + repo := &grokCredentialHandlerRepo{accounts: accounts, missingOnGet: map[int64]bool{}} + upstream := &preContentFailoverUpstream{} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.MaxAccountSwitches = 3 + cfg.Gateway.StreamKeepaliveInterval = 1 + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + gateway := service.NewOpenAIGatewayService( + repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, + service.NewBillingService(cfg, nil), nil, billingCache, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, + ) + cache := &concurrencyCacheMock{ + acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, + acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, + } + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, nil, nil, nil, cfg) + apiKey := &service.APIKey{ + ID: 9102, GroupID: &groupID, + User: &service.User{ID: 9103, Status: service.StatusActive}, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, AllowMessagesDispatch: true}, + } + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) + c.Next() + }) + router.POST("/v1/messages", h.Messages) + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString( + `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + return rec, upstream +} + +func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) { + rec, upstream := servePreContentFailoverMessages(t, 2) + + body := rec.Body.String() + require.Equal(t, 2, upstream.calls(), "body: %q", body) + require.Equal(t, 1, strings.Count(body, "event: message_start"), "body: %q", body) + require.Contains(t, body, "answer from second account") +} + +func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing.T) { + rec, upstream := servePreContentFailoverMessages(t, 1) + + body := rec.Body.String() + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.Contains(t, body, "event: ping") + lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:] + require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) + require.Contains(t, lastEvent, `"type":"error"`) + for _, line := range strings.Split(body, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} diff --git a/backend/internal/service/openai_compat_model_test.go b/backend/internal/service/openai_compat_model_test.go index 7bd000b4b8..97d1c5fd26 100644 --- a/backend/internal/service/openai_compat_model_test.go +++ b/backend/internal/service/openai_compat_model_test.go @@ -2159,7 +2159,10 @@ func TestForwardAsAnthropic_MissingTerminalAfterClientDisconnectSkipsOpsAndFailo c, _ := gin.CreateTestContext(rec) c.Writer = &openAICompatFailingWriter{ResponseWriter: c.Writer, failAfter: 0} body := []byte(`{"model":"gpt-5.4","max_tokens":16,"messages":[{"role":"user","content":"hello"}],"stream":true}`) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + // A real disconnect also cancels the request context. + reqCtx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)).WithContext(reqCtx) c.Request.Header.Set("Content-Type", "application/json") upstreamBody := strings.Join([]string{ diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..2422478c63 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1077,6 +1077,34 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( return out } + // Until the first content_block_delta the translated prelude is held, so a + // failure before any content reaches the client still fails over and the + // next attempt starts a fresh message. + var held strings.Builder + emit := func(sse string, release bool) error { + if !clientOutputStarted && !release { + _, _ = held.WriteString(sse) + return nil + } + writeStreamHeaders() + if held.Len() > 0 { + sse = held.String() + sse + held.Reset() + } + if _, err := fmt.Fprint(c.Writer, sse); err != nil { + return err + } + clientOutputStarted = true + return nil + } + // A failure that does not fail over still shows the client the prelude it + // would have seen without holding. + releaseHeld := func() { + if held.Len() > 0 && !clientDisconnected && emit("", true) == nil { + c.Writer.Flush() + } + } + // processDataLine handles a single "data: ..." SSE line from upstream. processDataLine := func(payload string) bool { payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) @@ -1130,12 +1158,11 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( UpstreamOutTok: usage.OutputTokens, }) if !clientDisconnected { - writeStreamHeaders() clientMsg := msg if clientMsg == "" { clientMsg = "Request blocked by upstream cyber-security policy" } - if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE("invalid_request_error", clientMsg)); err == nil { + if emit(buildAnthropicStreamErrorSSE("invalid_request_error", clientMsg), true) == nil { c.Writer.Flush() } clientDisconnected = true @@ -1168,14 +1195,11 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( MarkResponseCommitted(c) } if !clientDisconnected { - if !clientOutputStarted { + if !clientOutputStarted && held.Len() == 0 { writeAnthropicError(c, errStatus, errType, errMsg) clientOutputStarted = true - } else { - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, errMsg)); err == nil { - c.Writer.Flush() - } + } else if emit(buildAnthropicStreamErrorSSE(errType, errMsg), true) == nil { + c.Writer.Flush() } } streamNonFailoverErr = fmt.Errorf("upstream response failed: %s", errMsg) @@ -1195,18 +1219,18 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( ) continue } - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, sse); err != nil { + if err := emit(sse, isTerminalEvent || evt.Type == "content_block_delta"); err != nil { clientDisconnected = true logger.L().Info("openai messages stream: client disconnected, continuing to drain upstream for billing", zap.String("request_id", requestID), ) break } - clientOutputStarted = true } } - if len(events) > 0 && !clientDisconnected { + // gin's Flush commits the 200 header first; flushing while the prelude + // is held would make the attempt ineligible for failover. + if clientOutputStarted && len(events) > 0 && !clientDisconnected { c.Writer.Flush() } return isTerminalEvent @@ -1226,15 +1250,13 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( if err != nil { continue } - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, sse); err != nil { + if err := emit(sse, true); err != nil { clientDisconnected = true logger.L().Info("openai messages stream: client disconnected during final flush", zap.String("request_id", requestID), ) break } - clientOutputStarted = true } if !clientDisconnected { c.Writer.Flush() @@ -1254,6 +1276,9 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } } missingTerminalErr := func() (*OpenAIForwardResult, error) { + if !clientOutputStarted && c.Request.Context().Err() != nil { + clientDisconnected = true + } result := resultWithUsage() if clientDisconnected { return result, fmt.Errorf("stream usage incomplete: missing terminal event") @@ -1294,6 +1319,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if err := scanner.Err(); err != nil { handleScanErr(err) + releaseHeld() return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", err) } if frame, ok := parser.Finish(); ok { @@ -1375,6 +1401,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if ev.err != nil { handleScanErr(ev.err) + releaseHeld() return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", ev.err) } lastDataAt = time.Now() @@ -1403,18 +1430,26 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( zap.String("model", originalModel), zap.Duration("interval", streamInterval), ) + releaseHeld() return resultWithUsage(), fmt.Errorf("stream data interval timeout") case <-keepaliveCh: if clientDisconnected { continue } - if time.Since(lastDataAt) < keepaliveInterval { + // While the prelude is held nothing else reaches the client, so every + // tick pings. Account headers stay private and the bytes count as + // keepalive: the attempt that finally answers may be another one. + if clientOutputStarted && time.Since(lastDataAt) < keepaliveInterval { continue } - // Send Anthropic-format ping event - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n"); err != nil { + if clientOutputStarted { + writeStreamHeaders() + } else { + setSSEHeaders(c) + } + n, err := fmt.Fprint(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + if err != nil { // Client disconnected logger.L().Info("openai messages stream: client disconnected during keepalive", zap.String("request_id", requestID), @@ -1422,14 +1457,25 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( clientDisconnected = true continue } - clientOutputStarted = true + if !clientOutputStarted { + recordOpenAIStreamKeepaliveBytes(c, n) + } c.Writer.Flush() } } } // writeAnthropicError writes an error response in Anthropic Messages API format. +// Once the response is committed as SSE (keepalive pings went out), a bare JSON +// body would be unreadable to the client's SSE parser, so the error is written +// as an SSE error event instead. func writeAnthropicError(c *gin.Context, statusCode int, errType, message string) { + if c.Writer.Written() && strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") { + if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, message)); err == nil { + c.Writer.Flush() + } + return + } c.JSON(statusCode, gin.H{ "type": "error", "error": gin.H{ diff --git a/backend/internal/service/openai_gateway_messages_pre_content_test.go b/backend/internal/service/openai_gateway_messages_pre_content_test.go new file mode 100644 index 0000000000..250da3a03a --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_pre_content_test.go @@ -0,0 +1,165 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + preContentCreatedFrame = `data: {"type":"response.created","response":{"id":"resp_pre","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n" + preContentFailoverFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n" +) + +func newPreContentContext() (*httptest.ResponseRecorder, *gin.Context, []byte) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + return rec, c, body +} + +func forwardPreContent(t *testing.T, cfg *config.Config, header http.Header, upstreamBody io.ReadCloser) (*httptest.ResponseRecorder, *gin.Context, error) { + t.Helper() + rec, c, body := newPreContentContext() + if header == nil { + header = http.Header{} + } + header.Set("Content-Type", "text/event-stream") + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: header, Body: upstreamBody}} + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + _, err := svc.ForwardAsAnthropic(context.Background(), c, rawChatCompletionsTestAccount(), body, "", "") + return rec, c, err +} + +func TestForwardAsAnthropic_PreContentFailedFailsOver(t *testing.T) { + stream := preContentCreatedFrame + + `data: {"type":"response.in_progress","response":{"id":"resp_pre","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n" + + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"rs_1","type":"reasoning","summary":[]}}` + "\n\n" + + preContentFailoverFailed + rec, c, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(stream))) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "failure before content must fail over: %T: %v", err, err) + require.Empty(t, rec.Body.String()) + require.False(t, c.Writer.Written()) +} + +func TestForwardAsAnthropic_PreContentMissingTerminalFailsOver(t *testing.T) { + rec, c, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(preContentCreatedFrame))) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "EOF without a terminal event before content must fail over: %T: %v", err, err) + require.Empty(t, rec.Body.String()) + require.False(t, c.Writer.Written()) +} + +func TestForwardAsAnthropic_PreContentReadErrorDoesNotFailOver(t *testing.T) { + reader := &errAfterReader{data: strings.NewReader(preContentCreatedFrame), err: io.ErrUnexpectedEOF} + rec, _, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(reader)) + + require.ErrorIs(t, err, io.ErrUnexpectedEOF) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "a read error never fails over: %v", err) + require.Contains(t, rec.Body.String(), "message_start") +} + +func TestForwardAsAnthropic_PreContentPingKeepsFailover(t *testing.T) { + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.StreamKeepaliveInterval = 1 + pr, pw := io.Pipe() + go func() { + _, _ = io.WriteString(pw, preContentCreatedFrame) + time.Sleep(1300 * time.Millisecond) + _, _ = io.WriteString(pw, preContentFailoverFailed) + _ = pw.Close() + }() + rec, c, err := forwardPreContent(t, cfg, http.Header{"X-Request-Id": []string{"attempt-1"}}, pr) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "ping-only output must keep failover: %T: %v", err, err) + body := rec.Body.String() + require.GreaterOrEqual(t, strings.Count(body, "event: ping"), 1) + require.NotContains(t, body, "message_start") + require.Equal(t, "text/event-stream", rec.Header().Get("Content-Type")) + require.Empty(t, rec.Header().Get("X-Request-Id"), "account headers must stay private while the prelude is held") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) +} + +func TestForwardAsAnthropic_ContentReleasedNeverFailsOver(t *testing.T) { + stream := preContentCreatedFrame + + `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" + + preContentFailoverFailed + rec, _, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(stream))) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "released content must not fail over: %v", err) + body := rec.Body.String() + start := strings.Index(body, "event: message_start") + text := strings.Index(body, `"text":"partial"`) + errEvt := strings.Index(body, "event: error") + require.True(t, start >= 0 && text > start && errEvt > text, "body order: %q", body) +} + +func TestForwardAsAnthropic_TerminalBeforeContentReleasesPrelude(t *testing.T) { + stream := preContentCreatedFrame + + `data: {"type":"response.completed","response":{"id":"resp_pre","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":0,"total_tokens":3}}}` + "\n\n" + rec, _, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(stream))) + + require.NoError(t, err) + body := rec.Body.String() + start := strings.Index(body, "event: message_start") + delta := strings.Index(body, "event: message_delta") + stop := strings.Index(body, "event: message_stop") + require.True(t, start >= 0 && delta > start && stop > delta, "body order: %q", body) +} + +func TestForwardAsAnthropic_IntervalTimeoutReleasesPrelude(t *testing.T) { + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.StreamDataIntervalTimeout = 1 + pr, pw := io.Pipe() + defer func() { _ = pw.Close() }() + go func() { + _, _ = io.WriteString(pw, preContentCreatedFrame) + }() + rec, _, err := forwardPreContent(t, cfg, nil, pr) + + require.Error(t, err) + require.Contains(t, err.Error(), "stream data interval timeout") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.Contains(t, rec.Body.String(), "message_start") +} + +func TestWriteAnthropicErrorAfterCommittedSSE(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + setSSEHeaders(c) + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", "prompt is too long") + + body := rec.Body.String() + require.True(t, strings.HasSuffix(body, "event: error\ndata: {\"error\":{\"message\":\"prompt is too long\",\"type\":\"invalid_request_error\"},\"type\":\"error\"}\n\n"), "body: %q", body) + for _, line := range strings.Split(body, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} From 7349750c017ca0d4efbb63cc109c6692fcc4d228 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 06:50:16 -0800 Subject: [PATCH 62/85] fix(gateway): limit composite model rewrite to message_start events On the Anthropic forward streaming path the public model was written into any event carrying a message object, while the API key passthrough path only rewrites message_start. Rewrite message_start only on both. The passthrough path also added a model field to a message_start that had none, which the non-streaming path does not do. Skip the rewrite when the field is absent. --- .../composite_route_client_model_test.go | 79 +++++++++++++++++++ .../service/gateway_anthropic_passthrough.go | 2 +- .../service/gateway_upstream_response.go | 2 +- 3 files changed, 81 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/composite_route_client_model_test.go b/backend/internal/service/composite_route_client_model_test.go index cd3af8b80d..48444e2c19 100644 --- a/backend/internal/service/composite_route_client_model_test.go +++ b/backend/internal/service/composite_route_client_model_test.go @@ -218,3 +218,82 @@ func TestRestoreCompositeClientModelOnlyWhenRouteRewroteModel(t *testing.T) { noModel := []byte(`{"type":"error"}`) require.Equal(t, string(noModel), string(restoreCompositeClientModel(renamedCtx, noModel))) } + +func forwardCompositeAnthropicStream(t *testing.T, newAccount func() *Account, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + client := []byte(`{"model":"public-model","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client) + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := newForwardPartialUsageServiceForTest(upstream) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + + _, err = svc.Forward(ctx, c, newAccount(), parsed) + require.NoError(t, err) + return rec.Body.String() +} + +func anthropicStreamEventData(t *testing.T, sse, eventType string) string { + t.Helper() + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data:") + data = strings.TrimSpace(data) + if ok && gjson.Get(data, "type").String() == eventType { + return data + } + } + t.Fatalf("no %s event in stream:\n%s", eventType, sse) + return "" +} + +func TestCompositeRouteStreamRewritesOnlyMessageStartModel(t *testing.T) { + accounts := map[string]func() *Account{ + "oauth": newAnthropicOAuthAccountForPartialUsageTest, + "apikey-passthrough": newAnthropicAPIKeyAccountForTest, + } + for accountName, newAccount := range accounts { + t.Run(accountName, func(t *testing.T) { + sse := forwardCompositeAnthropicStream(t, newAccount, strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`, + "", + `event: ping`, + `data: {"type":"ping","message":{"model":"other-model"}}`, + "", + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + "", + `event: message_stop`, + `data: {"type":"message_stop"}`, + "", + "", + }, "\n")) + + require.Equal(t, "public-model", gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").String()) + require.Equal(t, "other-model", gjson.Get(anthropicStreamEventData(t, sse, "ping"), "message.model").String()) + }) + } +} + +func TestCompositeRoutePassthroughStreamKeepsMessageStartWithoutModel(t *testing.T) { + sse := forwardCompositeAnthropicStream(t, newAnthropicAPIKeyAccountForTest, strings.Join([]string{ + `event: message_start`, + `data:{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1}}}`, + "", + `event: message_stop`, + `data: {"type":"message_stop"}`, + "", + "", + }, "\n")) + + require.False(t, gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").Exists()) +} diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 59bb98ad36..063f5b96a6 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -561,7 +561,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } } - if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" { + if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" && gjson.Get(data, "message.model").Exists() { if rewritten, err := sjson.Set(data, "message.model", clientModel); err == nil { line = "data: " + rewritten } diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 8f360756c9..018a428892 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -993,7 +993,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } } } - if clientModel != "" { + if clientModel != "" && eventType == "message_start" { if msg, ok := event["message"].(map[string]any); ok { if _, ok := msg["model"].(string); ok { msg["model"] = clientModel From 94e56dd192c14b300d9dc514b276164263a5b160 Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 07:03:11 -0800 Subject: [PATCH 63/85] fix(upstream): do not fail the dial when TCP_USER_TIMEOUT cannot be set upstreamDialControl returned the setsockopt error, so a kernel or socket that refuses TCP_USER_TIMEOUT made every dial through newUpstreamDialer fail, where the keep-alive options alone never do that. A failure is now logged and the dial goes on without the option, as the standard library does for the keep-alive options. --- .../repository/http_upstream_keepalive_linux.go | 17 ++++++++++++----- .../http_upstream_keepalive_linux_test.go | 12 ++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/backend/internal/repository/http_upstream_keepalive_linux.go b/backend/internal/repository/http_upstream_keepalive_linux.go index 607a3120cf..68d7cd757e 100644 --- a/backend/internal/repository/http_upstream_keepalive_linux.go +++ b/backend/internal/repository/http_upstream_keepalive_linux.go @@ -2,20 +2,27 @@ package repository -import "syscall" +import ( + "log/slog" + "syscall" +) // tcpUserTimeout is TCP_USER_TIMEOUT from Linux include/uapi/linux/tcp.h; the // standard library's syscall package does not define it on linux/amd64. const tcpUserTimeout = 0x12 // upstreamDialControl sets TCP_USER_TIMEOUT on each upstream socket -// before it connects. -func upstreamDialControl(_, _ string, raw syscall.RawConn) error { +// before it connects. A failure is logged and the dial goes on without the +// option, like the standard library does for the keep-alive options. +func upstreamDialControl(network, _ string, raw syscall.RawConn) error { var sockErr error if err := raw.Control(func(fd uintptr) { sockErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, tcpUserTimeout, int(upstreamTCPUserTimeout.Milliseconds())) }); err != nil { - return err + sockErr = err } - return sockErr + if sockErr != nil { + slog.Warn("upstream_tcp_user_timeout_not_set", "network", network, "error", sockErr) + } + return nil } diff --git a/backend/internal/repository/http_upstream_keepalive_linux_test.go b/backend/internal/repository/http_upstream_keepalive_linux_test.go index ec1cfdf14d..c25e7458fc 100644 --- a/backend/internal/repository/http_upstream_keepalive_linux_test.go +++ b/backend/internal/repository/http_upstream_keepalive_linux_test.go @@ -71,3 +71,15 @@ func TestUpstreamDialerSetsKeepAliveAndUserTimeoutOnTheSocket(t *testing.T) { "TCP_USER_TIMEOUT": 30000, }, got) } + +// A socket option the kernel refuses must not fail the dial: TCP_USER_TIMEOUT +// does not apply to a UDP socket, so setting it there returns an error. +func TestUpstreamDialerIgnoresUserTimeoutFailure(t *testing.T) { + packetConn, err := net.ListenPacket("udp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = packetConn.Close() }) + + conn, err := newUpstreamDialer().DialContext(context.Background(), "udp", packetConn.LocalAddr().String()) + require.NoError(t, err) + require.NoError(t, conn.Close()) +} From c1c9d195b3a4c7f4af5673d032c12083d4ae8cb1 Mon Sep 17 00:00:00 2001 From: qsy4 <28869029+qsy4@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:24:36 -0800 Subject: [PATCH 64/85] fix(openai): forward upstream keepalive events before first output Problem: on native Responses streams the gateway stages every event of an attempt until the first semantic output, so it can still fail over to another account. Upstream keepalive events are staged with the rest. When the upstream is silent for a long time (long high-effort reasoning), the client only receives ":" comment heartbeats. Codex resets its stream idle timer on parsed SSE events only, so it gives up after its 300 second idle timeout ("idle timeout waiting for SSE") while the upstream is still working, and the gateway keeps reading a stream nobody will receive. Fix: while the first-output stage is open, write upstream keepalive events (both the "event: keepalive" + data form and the data-only form) straight to the client, the same way the comment keepalive bypasses the stage: only the stable SSE headers are committed, the attempt's lifecycle events and account headers stay private, and the bytes are recorded with recordOpenAIStreamKeepaliveBytes so they still do not count as client output and pre-output failover keeps working. The WebSocket to HTTP bridge already forwards keepalive before first output this way. Events after output started are unchanged. Keepalive events are not output, so they do not stop the first-output timer: with gateway.openai_first_output_timeout_seconds set, a stalled attempt still fails over on time while the client stays connected. Test: TestOpenAINativeStreamForwardsUpstreamKeepaliveBeforeFirstOutput covers both frame shapes. TestOpenAINativeStreamKeepaliveThenFailoverContinuesWithNextAccount checks that failover after a forwarded keepalive streams the next account from its start. TestOpenAINativeStreamKeepaliveDoesNotResetFirstOutputTimeout checks that paced keepalives do not postpone the timeout. TestOpenAINativeStreamKeepaliveAfterOutputStaysInOrder guards the post-output path. TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver, TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken and TestOpenAINativeMetadataAndKeepaliveDoNotDisarmFirstOutputTimeout asserted that the client receives nothing before first output on the native path. Their native cases now assert that only the upstream keepalive frames reach the client and that those bytes still do not count as output; the passthrough cases are unchanged. --- .../service/openai_capacity_shed_test.go | 13 ++ .../openai_gateway_response_handling.go | 41 ++++ ...i_gateway_stream_keepalive_forward_test.go | 215 ++++++++++++++++++ .../service/openai_visible_ttft_test.go | 4 +- 4 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/openai_gateway_stream_keepalive_forward_test.go diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index 6737e42cbd..ae060c02dd 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -241,6 +241,13 @@ func TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver(t *testing.T) { require.True(t, failoverErr.RequestScopedTransient) require.Equal(t, http.StatusServiceUnavailable, failoverErr.ClientStatusCode) require.Contains(t, failoverErr.ClientMessage, "servers are currently overloaded") + if tt.name == "native" { + // Only the upstream keepalive events reach the client before first output. + require.Equal(t, "event: keepalive\ndata: {\"type\":\"keepalive\"}\n\ndata: {\"type\":\"keepalive\"}\n\n", rec.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + require.Empty(t, rec.Header().Get("X-Request-Id")) + return + } require.False(t, c.Writer.Written()) require.Empty(t, rec.Body.String()) }) @@ -354,6 +361,12 @@ func TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken(t *testing.T) { require.ErrorAs(t, err, &failoverErr) require.True(t, failoverErr.RetryableOnSameAccount) require.True(t, failoverErr.RequestScopedTransient) + if !passthrough { + // Only the upstream keepalive event reaches the client before first output. + require.Equal(t, "data: {\"type\":\"keepalive\"}\n\n", rec.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + return + } require.Empty(t, rec.Body.String()) }) } diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index ae528e4fea..3d1d67af84 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -484,6 +484,25 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. sendErrorEvent(code, message) return resultWithUsage(), fmt.Errorf("stream read error: %w", scanErr), true } + // Upstream keepalive events bypass the first-output stage the same way the + // comment keepalive does: Codex resets its stream idle timer only on parsed + // SSE events, while the attempt's lifecycle events and account headers stay + // private until semantic output. The bytes do not count as client output. + keepaliveEventDirect := false + forwardsKeepaliveDirect := func(eventType string) bool { + return eventType == "keepalive" && stageFirstOutput && !firstOutputStage.closed && !failureDelivered && !suppressCurrentEvent + } + writeKeepaliveDirect := func(value string) { + if clientDisconnected { + return + } + n, err := w.Write([]byte(value)) + recordOpenAIStreamKeepaliveBytes(c, n) + if err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") + } + } processSSELine := func(line string, queueDrained bool) { if streamEarlyErr != nil { return @@ -492,11 +511,23 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. pendingSSEEventType = eventType eventType = strings.TrimSpace(eventType) suppressCurrentEvent = codexFailureTerminal && (eventType == "error" || (sawBareError && !sawResponseFailed && eventType != "response.failed")) + if forwardsKeepaliveDirect(eventType) { + keepaliveEventDirect = true + eventInProgress = true + writeKeepaliveDirect(line + "\n") + return + } } // Extract data from SSE line (supports both "data: " and "data:" formats) if data, ok := extractOpenAISSEDataLine(line); ok { dataBytes := []byte(data) eventType := effectiveOpenAISSEEventType(dataBytes, pendingSSEEventType) + if keepaliveEventDirect || forwardsKeepaliveDirect(eventType) { + keepaliveEventDirect = true + eventInProgress = true + writeKeepaliveDirect(line + "\n") + return + } if codexFailureTerminal && sawBareError && !sawResponseFailed && (eventType == "response.completed" || eventType == "response.done") { // A later successful terminal is authoritative over a pending bare @@ -748,6 +779,16 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // A blank line dispatches a guarded event from the attempt-local stage. if stageFirstOutput && line == "" { pendingSSEEventType = "" + if keepaliveEventDirect { + keepaliveEventDirect = false + eventInProgress = false + writeKeepaliveDirect("\n") + if !clientDisconnected { + flusher.Flush() + lastDownstreamWriteAt = time.Now() + } + return + } if suppressCurrentEvent { suppressCurrentEvent = false terminalFailurePending = false diff --git a/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go b/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go new file mode 100644 index 0000000000..d83e2a3d41 --- /dev/null +++ b/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go @@ -0,0 +1,215 @@ +package service + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// keepaliveForwardBody holds the upstream stream open until the gateway closes it. +type keepaliveForwardBody struct { + io.ReadCloser + closed chan struct{} + once sync.Once +} + +func (b *keepaliveForwardBody) Close() error { + b.once.Do(func() { close(b.closed) }) + return b.ReadCloser.Close() +} + +// stalledKeepaliveResponse returns an upstream response that sends the preamble and the given +// keepalive frames, then produces no semantic output until it is closed. +func stalledKeepaliveResponse(frames ...string) *http.Response { + pr, pw := io.Pipe() + body := &keepaliveForwardBody{ReadCloser: pr, closed: make(chan struct{})} + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_stalled\"}}\n\n")) + _, _ = pw.Write([]byte("data: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_stalled\"}}\n\n")) + for _, frame := range frames { + _, _ = pw.Write([]byte(frame)) + } + select { + case <-body.closed: + case <-time.After(5 * time.Second): + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"request-stalled"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: body, + } +} + +func newKeepaliveForwardService(firstOutputTimeoutSeconds int) *OpenAIGatewayService { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: firstOutputTimeoutSeconds, + MaxLineSize: defaultMaxLineSize, + }} + return &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} +} + +func newKeepaliveForwardContext() (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + return c, rec +} + +const ( + upstreamKeepaliveData = `data: {"type":"keepalive","sequence_number":3}` + upstreamKeepaliveEvent = "event: keepalive\n" + upstreamKeepaliveData + "\n\n" +) + +// Codex resets its stream idle timer only on parsed SSE events, so the upstream keepalive event +// must reach the client before the first semantic output, while the attempt's preamble and +// account headers stay private and the bytes still do not count as client output. +func TestOpenAINativeStreamForwardsUpstreamKeepaliveBeforeFirstOutput(t *testing.T) { + for _, tc := range []struct { + name string + frame string + }{ + {"event_and_data", upstreamKeepaliveEvent}, + {"data_only", upstreamKeepaliveData + "\n\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + _, err := svc.handleStreamingResponse(c.Request.Context(), stalledKeepaliveResponse(tc.frame), c, + &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr, "no semantic output: the first-output timeout must fail over") + require.Equal(t, tc.frame, rec.Body.String(), "only the upstream keepalive event reaches the client, verbatim") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "keepalive bytes are not client output") + require.Empty(t, rec.Result().Header.Values("X-Request-Id"), "account headers stay private before output") + require.Empty(t, rec.Result().Header.Values("X-Ratelimit-Remaining-Requests")) + }) + } +} + +// After a pre-output failover the next account's stream continues the same response: the client +// sees the first account's keepalive, then the second account's complete stream from its start. +func TestOpenAINativeStreamKeepaliveThenFailoverContinuesWithNextAccount(t *testing.T) { + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + _, firstErr := svc.handleStreamingResponse(c.Request.Context(), stalledKeepaliveResponse(upstreamKeepaliveEvent), c, + &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, firstErr, &failoverErr) + + secondResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{"request-second"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_second"}}`, + "", + `data: {"type":"response.output_text.delta","delta":"hello"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_second","usage":{"input_tokens":1,"output_tokens":1}}}`, + "", + }, "\n"))), + } + result, secondErr := svc.handleStreamingResponse(c.Request.Context(), secondResp, c, + &Account{ID: 2, Platform: PlatformOpenAI}, time.Now(), "model", "model") + require.NoError(t, secondErr) + require.NotNil(t, result) + + body := rec.Body.String() + require.True(t, strings.HasPrefix(body, upstreamKeepaliveEvent), "first account's keepalive comes first, got %q", body) + require.NotContains(t, body, "resp_stalled", "the failed attempt's preamble never reaches the client") + created := strings.Index(body, `"id":"resp_second"`) + require.Greater(t, created, len(upstreamKeepaliveEvent)-1) + require.Less(t, created, strings.Index(body, `"delta":"hello"`)) + require.Empty(t, rec.Result().Header.Values("X-Request-Id"), "headers were committed by the keepalive, not the second account") +} + +// Keepalive events after output started keep their place in the stream: not dropped, not repeated. +func TestOpenAINativeStreamKeepaliveAfterOutputStaysInOrder(t *testing.T) { + svc := newKeepaliveForwardService(0) + c, rec := newKeepaliveForwardContext() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_order"}}`, + "", + `data: {"type":"response.output_text.delta","delta":"a"}`, + "", + "event: keepalive", + upstreamKeepaliveData, + "", + `data: {"type":"response.output_text.delta","delta":"b"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_order","usage":{"input_tokens":1,"output_tokens":2}}}`, + "", + }, "\n"))), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + require.NoError(t, err) + + body := rec.Body.String() + require.Equal(t, 1, strings.Count(body, `"type":"keepalive"`)) + a, ka, b := strings.Index(body, `"delta":"a"`), strings.Index(body, upstreamKeepaliveEvent), strings.Index(body, `"delta":"b"`) + require.True(t, a < ka && ka < b, "keepalive must stay between the deltas, got %q", body) +} + +// Forwarded keepalive events are not output: they must not postpone the first-output timeout, +// so an attempt whose upstream only keeps the stream alive still fails over on time. +func TestOpenAINativeStreamKeepaliveDoesNotResetFirstOutputTimeout(t *testing.T) { + pr, pw := io.Pipe() + body := &keepaliveForwardBody{ReadCloser: pr, closed: make(chan struct{})} + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_paced\"}}\n\n")) + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + deadline := time.After(4 * time.Second) + for { + select { + case <-body.closed: + return + case <-deadline: + return + case <-ticker.C: + if _, err := pw.Write([]byte(upstreamKeepaliveEvent)); err != nil { + return + } + } + } + }() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: body, + } + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + started := time.Now() + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, started, "model", "model") + elapsed := time.Since(started) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Less(t, elapsed, 2500*time.Millisecond, "keepalive events must not reset the first-output timer") + require.GreaterOrEqual(t, strings.Count(rec.Body.String(), upstreamKeepaliveEvent), 2, "keepalives reached the client before the timeout") + require.NotContains(t, rec.Body.String(), "resp_paced") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) +} diff --git a/backend/internal/service/openai_visible_ttft_test.go b/backend/internal/service/openai_visible_ttft_test.go index 24a60e21e2..87497f39f0 100644 --- a/backend/internal/service/openai_visible_ttft_test.go +++ b/backend/internal/service/openai_visible_ttft_test.go @@ -98,7 +98,9 @@ func TestOpenAINativeMetadataAndKeepaliveDoNotDisarmFirstOutputTimeout(t *testin var failoverErr *UpstreamFailoverError require.ErrorAs(t, err, &failoverErr) require.True(t, failoverErr.SafeToFailoverAfterWrite) - require.Empty(t, recorder.Body.String()) + // Only the upstream keepalive event reaches the client; it is not output. + require.Equal(t, "data: {\"type\":\"keepalive\"}\n\n", recorder.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) select { case <-writerDone: case <-time.After(time.Second): From 975b2807d12966823ace2428290ce53c72d59dc6 Mon Sep 17 00:00:00 2001 From: qsy4 <28869029+qsy4@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:56:58 -0800 Subject: [PATCH 65/85] fix(openai): apply account side effects to stream errors after output on compat paths Problem: on /v1/chat/completions and /v1/messages the upstream responses stream is converted as it arrives, so client output starts with the first event (a role chunk or message_start written for response.created). A terminal error event that arrives after that can no longer fail over, and the branch that handles it only records the error. Unlike /v1/responses and the WebSocket forwarder, which call handleOpenAIStreamTerminalAccountSideEffects in the same situation, the account health is never updated: a rate limited, quota exhausted or deauthorized account stays schedulable and every new request routed to it fails the same way. Fix: call handleOpenAIStreamTerminalAccountSideEffects in the non-failover branch of both compat stream handlers, before the error is recorded, with the same arguments the failover constructor uses. The failover branch is unchanged; it already applies the side effects inside newOpenAIStreamFailoverErrorWithModel, so each upstream attempt is still counted once. Test: TestForwardAsChatCompletions_StreamErrorAfterOutputAppliesAccountSideEffects and TestForwardAsAnthropic_StreamErrorAfterOutputAppliesAccountSideEffects check that an auth error after output marks the account exactly once. The two StreamErrorBeforeOutputCountsOnce tests check that the failover path still marks the account exactly once. --- .../openai_gateway_chat_completions.go | 1 + ...compat_stream_account_side_effects_test.go | 145 ++++++++++++++++++ .../service/openai_gateway_messages.go | 1 + 3 files changed, 147 insertions(+) create mode 100644 backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index c340de7c49..0019471208 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -974,6 +974,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header) return true } + s.handleOpenAIStreamTerminalAccountSideEffects(c, account, payloadBytes, message, resp.Header, upstreamModel) message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message) defaultStatus, defaultErrType, defaultMsg := http.StatusBadGateway, "upstream_error", message // 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致), diff --git a/backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go b/backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go new file mode 100644 index 0000000000..a6f47ec8d4 --- /dev/null +++ b/backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go @@ -0,0 +1,145 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// compatStreamSideEffectsRepo records the account-health writes made by the rate limit service. +type compatStreamSideEffectsRepo struct { + stubOpenAIAccountRepo + rateLimitCalls []time.Time + errorCalls []string +} + +func (r *compatStreamSideEffectsRepo) SetRateLimited(_ context.Context, _ int64, resetAt time.Time) error { + r.rateLimitCalls = append(r.rateLimitCalls, resetAt) + return nil +} + +func (r *compatStreamSideEffectsRepo) SetError(_ context.Context, _ int64, msg string) error { + r.errorCalls = append(r.errorCalls, msg) + return nil +} + +func compatStreamSideEffectsAccount() Account { + return Account{ + ID: 601, + Name: "openai-apikey-compat-stream", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + } +} + +// compatStreamSideEffectsSSE builds an upstream responses stream that fails with errorEvent. +// With outputFirst the error follows response.created and a text delta, so client output has +// started (in practice response.created alone already starts it on both compat paths); without, +// the error is the first event and the request can still fail over. +func compatStreamSideEffectsSSE(outputFirst bool, errorEvent string) string { + var lines []string + if outputFirst { + lines = append(lines, + `data: {"type":"response.created","response":{"id":"resp_side","model":"gpt-5.5","status":"in_progress","output":[]}}`, + "", + `data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}`, + "", + ) + } + lines = append(lines, `event: error`, `data: `+errorEvent, "") + return strings.Join(lines, "\n") +} + +const compatStreamAuthErrorEvent = `{"type":"error","status":401,"error":{"code":"invalid_api_key","type":"invalid_request_error","message":"Incorrect API key provided"}}` + +func newCompatStreamSideEffectsService(sse string) (*OpenAIGatewayService, *compatStreamSideEffectsRepo, *Account) { + account := compatStreamSideEffectsAccount() + repo := &compatStreamSideEffectsRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}} + svc := &OpenAIGatewayService{ + accountRepo: repo, + rateLimitService: &RateLimitService{accountRepo: repo}, + httpUpstream: &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_side"}}, + Body: io.NopCloser(strings.NewReader(sse)), + }}, + } + return svc, repo, &account +} + +func newCompatStreamContext(path string, body []byte) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + return c, rec +} + +// A terminal stream error that arrives after client output started can no longer fail over, but the +// account health still has to be updated — otherwise the account stays schedulable and every new +// request routed to it fails the same way. +func TestForwardAsChatCompletions_StreamErrorAfterOutputAppliesAccountSideEffects(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(true, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, rec := newCompatStreamContext("/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "output already started: must not fail over") + require.Contains(t, rec.Body.String(), "partial", "client output must have started before the error") + require.Len(t, repo.errorCalls, 1, "auth failure after output must mark the account exactly once") + require.Empty(t, repo.rateLimitCalls) +} + +func TestForwardAsAnthropic_StreamErrorAfterOutputAppliesAccountSideEffects(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(true, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, rec := newCompatStreamContext("/v1/messages", body) + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "output already started: must not fail over") + require.Contains(t, rec.Body.String(), "partial", "client output must have started before the error") + require.Len(t, repo.errorCalls, 1, "auth failure after output must mark the account exactly once") + require.Empty(t, repo.rateLimitCalls) +} + +// Before client output the error fails over; the failover constructor already applies the side +// effects, so the account is marked once — not once per path. +func TestForwardAsChatCompletions_StreamErrorBeforeOutputCountsOnce(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(false, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, _ := newCompatStreamContext("/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "no output yet: must fail over, got %v", err) + require.Len(t, repo.errorCalls, 1, "failover path must not double count") +} + +func TestForwardAsAnthropic_StreamErrorBeforeOutputCountsOnce(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(false, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, _ := newCompatStreamContext("/v1/messages", body) + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "no output yet: must fail over, got %v", err) + require.Len(t, repo.errorCalls, 1, "failover path must not double count") +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..651448af91 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1154,6 +1154,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header) return true } + s.handleOpenAIStreamTerminalAccountSideEffects(c, account, payloadBytes, message, resp.Header, upstreamModel) message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message) errStatus, errType, errMsg := http.StatusBadGateway, "api_error", message // 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致), From f1013f177f7a5918af5816f0235a61ea71699efd Mon Sep 17 00:00:00 2001 From: Anankke Date: Sat, 14 Nov 2026 07:07:17 -0800 Subject: [PATCH 66/85] fix(openai): SSE errors after keepalive, passthrough rules on exhaustion Once keepalive has committed the response as SSE, failover can continue, so every later error in the Messages loop must be an SSE event. ensureAnthropicErrorResponse no longer counts keepalive-only output as a written response, and the OpenCode unsupported-model error goes through writeAnthropicError. A failover-eligible failed or error frame no longer ends the stream inline but reaches the exhaustion path, so the failover error now carries the frame and exhaustion applies the error passthrough rule that matches it, as the inline path did. The lookup also runs for a first event frame and a stream=false request, where main skipped it. --- .../handler/openai_gateway_handler.go | 12 +- ...eway_messages_pre_content_failover_test.go | 259 +++++++++++++++--- backend/internal/service/gateway_service.go | 1 + ...penai_gateway_messages_pre_content_test.go | 23 ++ .../service/openai_gateway_passthrough.go | 30 ++ backend/internal/service/opencode_go.go | 8 +- 6 files changed, 292 insertions(+), 41 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index d2413ae82a..3e3b4d83c5 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1668,16 +1668,24 @@ func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted) return } + // A failed or error frame that triggered the failover no longer reaches the + // client in-band, so its error passthrough rule is applied here instead. + if status, errType, msg, ok := service.ApplyOpenAIStreamFailedFrameRule(c, failoverErr); ok { + h.anthropicStreamingAwareError(c, status, errType, msg, streamStarted) + return + } status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode) h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted) } // ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written. func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool { - if c == nil || c.Writer == nil || c.Writer.Written() { + // Keepalive pings alone do not count as a written response, but they do + // commit the response as SSE, so the fallback must then be an SSE event. + if c == nil || c.Writer == nil || service.OpenAICompactKeepaliveAdjustedWrittenSize(c) >= 0 { return false } - h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted) + h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted || c.Writer.Written()) return true } diff --git a/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go b/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go index 6db9679fb6..d20ea235be 100644 --- a/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go +++ b/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go @@ -14,10 +14,13 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/model" "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "go.uber.org/zap" ) const ( @@ -29,13 +32,13 @@ const ( `data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n" ) -// preContentFailoverUpstream answers the first request with a stream that stalls -// past one keepalive tick and then fails before any content; later requests -// complete normally. +// preContentFailoverUpstream hands each upstream request to respond, which +// gets the 1-based call number. type preContentFailoverUpstream struct { service.HTTPUpstream - mu sync.Mutex - hits []int64 + mu sync.Mutex + hits []int64 + respond func(call int) (*http.Response, error) } func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { @@ -44,20 +47,9 @@ func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID i } u.mu.Lock() u.hits = append(u.hits, accountID) - first := len(u.hits) == 1 + call := len(u.hits) u.mu.Unlock() - header := http.Header{"Content-Type": []string{"text/event-stream"}} - if !first { - return &http.Response{StatusCode: http.StatusOK, Header: header, Body: io.NopCloser(strings.NewReader(preContentHandlerSuccess))}, nil - } - pr, pw := io.Pipe() - go func() { - _, _ = io.WriteString(pw, preContentHandlerCreated) - time.Sleep(1300 * time.Millisecond) - _, _ = io.WriteString(pw, preContentHandlerFailed) - _ = pw.Close() - }() - return &http.Response{StatusCode: http.StatusOK, Header: header, Body: pr}, nil + return u.respond(call) } func (u *preContentFailoverUpstream) calls() int { @@ -66,20 +58,65 @@ func (u *preContentFailoverUpstream) calls() int { return len(u.hits) } -func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) { - t.Helper() - gin.SetMode(gin.TestMode) - groupID := int64(9101) - accounts := make([]service.Account, 0, accountCount) - for i := 0; i < accountCount; i++ { +func preContentSSEResponse(body io.ReadCloser) *http.Response { + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body} +} + +// preContentStallThenFail stalls past one keepalive tick after the first event +// and then fails with failed. +func preContentStallThenFail(failed string) *http.Response { + pr, pw := io.Pipe() + go func() { + _, _ = io.WriteString(pw, preContentHandlerCreated) + time.Sleep(1300 * time.Millisecond) + _, _ = io.WriteString(pw, failed) + _ = pw.Close() + }() + return preContentSSEResponse(pr) +} + +type unexpectedEOFReader struct{} + +func (unexpectedEOFReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF } + +type preContentFailoverScenario struct { + accounts []service.Account + respond func(call int) (*http.Response, error) + passthrough *service.ErrorPassthroughService + requestBody string +} + +func preContentAccounts(count int) []service.Account { + accounts := make([]service.Account, 0, count) + for i := 0; i < count; i++ { accounts = append(accounts, service.Account{ ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1, Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"}, }) } - repo := &grokCredentialHandlerRepo{accounts: accounts, missingOnGet: map[int64]bool{}} - upstream := &preContentFailoverUpstream{} + return accounts +} + +func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) { + t.Helper() + return serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(accountCount), + respond: func(call int) (*http.Response, error) { + if call == 1 { + return preContentStallThenFail(preContentHandlerFailed), nil + } + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerSuccess))), nil + }, + }) +} + +func serveMessagesScenario(t *testing.T, sc preContentFailoverScenario) (*httptest.ResponseRecorder, *preContentFailoverUpstream) { + t.Helper() + gin.SetMode(gin.TestMode) + groupID := int64(9101) + repo := &grokCredentialHandlerRepo{accounts: sc.accounts, missingOnGet: map[int64]bool{}} + upstream := &preContentFailoverUpstream{respond: sc.respond} cfg := &config.Config{RunMode: config.RunModeSimple} cfg.Gateway.MaxAccountSwitches = 3 cfg.Gateway.StreamKeepaliveInterval = 1 @@ -95,7 +132,7 @@ func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest. acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, } - h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, nil, nil, nil, cfg) + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, sc.passthrough, nil, nil, cfg) apiKey := &service.APIKey{ ID: 9102, GroupID: &groupID, User: &service.User{ID: 9103, Status: service.StatusActive}, @@ -105,18 +142,34 @@ func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest. router.Use(func(c *gin.Context) { c.Set(string(middleware.ContextKeyAPIKey), apiKey) c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) + service.BindErrorPassthroughService(c, sc.passthrough) c.Next() }) router.POST("/v1/messages", h.Messages) rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString( - `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`)) + requestBody := sc.requestBody + if requestBody == "" { + requestBody = `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}` + } + req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString(requestBody)) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(rec, req) return rec, upstream } +// requireEndsWithSSEError checks that a response already committed as SSE ends +// with an Anthropic error event and never carries a bare JSON line. +func requireEndsWithSSEError(t *testing.T, body string) { + t.Helper() + lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:] + require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) + require.Contains(t, lastEvent, `"type":"error"`) + for _, line := range strings.Split(body, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} + func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) { rec, upstream := servePreContentFailoverMessages(t, 2) @@ -132,10 +185,152 @@ func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing body := rec.Body.String() require.Equal(t, 1, upstream.calls(), "body: %q", body) require.Contains(t, body, "event: ping") + requireEndsWithSSEError(t, body) +} + +func TestOpenAIMessagesFailoverThenSecondAccountReadErrorEndsWithSSEError(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(2), + respond: func(call int) (*http.Response, error) { + if call == 1 { + return preContentStallThenFail(preContentHandlerFailed), nil + } + return preContentSSEResponse(io.NopCloser(unexpectedEOFReader{})), nil + }, + }) + + body := rec.Body.String() + require.Equal(t, 2, upstream.calls(), "body: %q", body) + require.NotContains(t, body, "message_start") + requireEndsWithSSEError(t, body) +} + +func TestOpenAIMessagesFailoverThenSecondAccountCredentialErrorEndsWithSSEError(t *testing.T) { + accounts := preContentAccounts(2) + accounts[1].Credentials = map[string]any{"base_url": "http://upstream.example"} + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: accounts, + respond: func(call int) (*http.Response, error) { + return preContentStallThenFail(preContentHandlerFailed), nil + }, + }) + + body := rec.Body.String() + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.NotContains(t, body, "message_start") + requireEndsWithSSEError(t, body) +} + +func TestOpenAIMessagesSlotAcquireFailureAfterKeepaliveIsSSE(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Header("Content-Type", "text/event-stream") + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + streamStarted := true + + h := &OpenAIGatewayHandler{} + selection := &service.AccountSelectionResult{Account: &service.Account{ID: 9201}} + _, result := h.acquireResponsesAccountSlot(c, nil, "", selection, true, &streamStarted, zap.NewNop()) + + require.Equal(t, openAISlotAcquireFailed, result) + body := rec.Body.String() lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:] require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) - require.Contains(t, lastEvent, `"type":"error"`) - for _, line := range strings.Split(body, "\n") { - require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) +} + +func newFailedFrameCodeRule(code string) *service.ErrorPassthroughService { + status := http.StatusTeapot + rule := &model.ErrorPassthroughRule{ + ID: 1, Name: "frame code rule", Enabled: true, Priority: 1, + Keywords: []string{code}, MatchMode: model.MatchModeAny, + Platforms: []string{model.PlatformOpenAI}, ResponseCode: &status, PassthroughBody: true, } + return service.NewErrorPassthroughService(&errorPassthroughRepoStub{rules: []*model.ErrorPassthroughRule{rule}}, nil) +} + +// A failed frame that triggers a failover is no longer written in-band, so its +// passthrough rule has to apply once the failover is exhausted. The rule is +// keyed on the frame's own code, which the generic failover envelope lacks. +func TestOpenAIMessagesFailoverExhaustedAppliesFailedFrameRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + respond: func(call int) (*http.Response, error) { + failed := `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n" + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + failed))), nil + }, + }) + + body := rec.Body.String() + t.Logf("status=%d body=%q", rec.Code, body) + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body) + require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body) + require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body) +} + +const preContentRateLimitFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n" + +func requireFailedFrameRuleJSON(t *testing.T, rec *httptest.ResponseRecorder) { + t.Helper() + body := rec.Body.String() + t.Logf("status=%d content-type=%q body=%q", rec.Code, rec.Header().Get("Content-Type"), body) + require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body) + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body) + require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body) +} + +// The failed frame is the first event of the stream, so it triggers the +// failover before any output and used to reach the generic mapping unchecked. +func TestOpenAIMessagesFirstEventFailedFrameExhaustedAppliesRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + respond: func(call int) (*http.Response, error) { + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentRateLimitFailed))), nil + }, + }) + + require.Equal(t, 1, upstream.calls()) + requireFailedFrameRuleJSON(t, rec) +} + +func TestOpenAIMessagesNonStreamFailedFrameExhaustedAppliesRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + requestBody: `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`, + respond: func(call int) (*http.Response, error) { + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + preContentRateLimitFailed))), nil + }, + }) + + require.Equal(t, 1, upstream.calls()) + requireFailedFrameRuleJSON(t, rec) +} + +// A failover triggered by an HTTP status keeps the built-in exhaustion mapping: +// no passthrough rule is looked up for it. +func TestOpenAIMessagesHTTPStatusFailoverExhaustedIgnoresPassthroughRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + respond: func(call int) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusBadGateway, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}`)), + }, nil + }, + }) + + body := rec.Body.String() + t.Logf("status=%d body=%q", rec.Code, body) + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.NotEqual(t, http.StatusTeapot, rec.Code, "body: %q", body) + require.Equal(t, "Upstream service temporarily unavailable", gjson.Get(body, "error.message").String(), "body: %q", body) } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..260a8c4993 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -712,6 +712,7 @@ type UpstreamFailoverError struct { NextAccountAction NextAccountAction ClientStatusCode int ClientMessage string + StreamFailedFrame *OpenAIStreamFailedFrame // 触发本次 failover 的流内 failed/error 帧;耗尽时用于错误透传规则匹配 } func (e *UpstreamFailoverError) Error() string { diff --git a/backend/internal/service/openai_gateway_messages_pre_content_test.go b/backend/internal/service/openai_gateway_messages_pre_content_test.go index 250da3a03a..5c911ee68b 100644 --- a/backend/internal/service/openai_gateway_messages_pre_content_test.go +++ b/backend/internal/service/openai_gateway_messages_pre_content_test.go @@ -163,3 +163,26 @@ func TestWriteAnthropicErrorAfterCommittedSSE(t *testing.T) { require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) } } + +func TestForwardAsAnthropic_OpenCodeUnsupportedModelAfterCommittedSSEIsSSEError(t *testing.T) { + rec, c, body := newPreContentContext() + body = []byte(`{"model":"gemini-3-pro","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + setSSEHeaders(c) + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + account := &Account{ + ID: 1, Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"}, + } + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig()} + + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + + require.Error(t, err) + out := rec.Body.String() + lastEvent := out[strings.LastIndex(strings.TrimRight(out, "\n"), "\n\n")+2:] + require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) + for _, line := range strings.Split(out, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index bf3debe638..5b5ec000d8 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1557,6 +1557,33 @@ func applyOpenAIStreamFailedErrorPassthroughRule( ) } +// OpenAIStreamFailedFrame is the in-stream failed or error frame behind a +// failover, kept so an exhausted failover can still apply the error +// passthrough rules that would have matched the frame. +type OpenAIStreamFailedFrame struct { + Platform string + Payload []byte + Message string +} + +// ApplyOpenAIStreamFailedFrameRule applies the error passthrough rules to the +// frame that triggered an exhausted failover, matching it the way +// applyOpenAIStreamFailedErrorPassthroughRule does for an in-band frame. +func ApplyOpenAIStreamFailedFrameRule(c *gin.Context, failoverErr *UpstreamFailoverError) (status int, errType string, errMsg string, matched bool) { + if failoverErr == nil || failoverErr.StreamFailedFrame == nil { + return 0, "", "", false + } + frame := failoverErr.StreamFailedFrame + status, errType, errMsg, matched = applyOpenAIStreamFailedErrorPassthroughRule(c, frame.Platform, frame.Payload, frame.Message) + if !matched { + return 0, "", "", false + } + if errMsg == "" { + errMsg = frame.Message + } + return status, errType, errMsg, true +} + func openAIStreamFailedEventShouldFailover(payload []byte, message string) bool { if hit, _, _ := detectOpenAICyberPolicy(payload); hit { return false @@ -1792,6 +1819,9 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel( classificationHeaders = nil } failoverErr := s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, headers, classificationHeaders, payload, message, shouldDisable, retryableOnSameAccount) + if len(payload) > 0 && account != nil { + failoverErr.StreamFailedFrame = &OpenAIStreamFailedFrame{Platform: account.Platform, Payload: payload, Message: message} + } if failoverErr.IsCredentialFailure() || failoverErr.RequestScopedTransient { return failoverErr } diff --git a/backend/internal/service/opencode_go.go b/backend/internal/service/opencode_go.go index 248ced9589..7709cb55e3 100644 --- a/backend/internal/service/opencode_go.go +++ b/backend/internal/service/opencode_go.go @@ -82,13 +82,7 @@ func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model msg := fmt.Sprintf("Model '%s' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)", model) if c != nil { if isAnthropic { - c.JSON(http.StatusBadRequest, gin.H{ - "type": "error", - "error": gin.H{ - "type": "invalid_request_error", - "message": msg, - }, - }) + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", msg) } else { c.JSON(http.StatusBadRequest, gin.H{ "error": gin.H{ From 2101f4f94005518529f0b391d823ef1cd2ade4c5 Mon Sep 17 00:00:00 2001 From: feeeei Date: Fri, 13 Nov 2026 16:36:16 +0800 Subject: [PATCH 67/85] =?UTF-8?q?perf(billing):=20=E5=90=8C=E4=B8=80?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=9A=84=E6=89=A3=E8=B4=B9=E6=8C=89=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E9=80=9A=E9=81=93=E5=90=88=E5=B9=B6=E7=BB=93=E7=AE=97?= =?UTF-8?q?=EF=BC=8C=E6=B6=88=E9=99=A4=E4=BD=99=E9=A2=9D=E7=83=AD=E7=82=B9?= =?UTF-8?q?=E8=A1=8C=E6=8E=92=E9=98=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 每个请求一个扣费事务时,同一用户的 UPDATE users SET balance 在同一行上排队抢行锁,单用户吞吐 约 1000 RPS;用量队列溢出转同步扣费后,延迟升到十几秒、内存涨到 GB 级。 - 新增 UsageBillingLaneCombiner 作为 UsageBillingRepository 注入:按用户 id 分 64 片,每个用户 一条结算通道。通道空闲时请求立即走单条 Apply;结算进行中到达的请求排队,下一轮最多 128 条在 一个事务内由 ApplyBatch 结算,每个调用方拿到自己的结果。不设攒批等待计时器,也不设配置开关。 - ApplyBatch 与按顺序逐条 Apply 等价:批量认领 usage_billing_dedup(指纹冲突、归档命中按条返回), 每个用户只扣一次余额;透支、Key 额度耗尽、账号额度越线等逐条结果用 decimal 前缀和还原。加锁 顺序为 user_subscriptions → users → api_keys → accounts,表内按 id 升序。账号额度越线时每批 每个账号写一条 scheduler outbox。 - 批量返回错误或 panic 时整批回滚,逐条回退到单条 Apply,共用一个截止时间;排队请求的结算超时 从结算开始时计。 - applyUsageBilling 在 Apply 返回后用独立超时做鉴权缓存失效与余额缓存同步。 - BatchUpdateLastUsed 在同一事务内先按 id 升序 FOR NO KEY UPDATE 锁定账号行再更新,不阻塞引用 accounts 的外键检查。 - 停机时 cleanup 等待各通道排空,之后的请求直连仓储。 bench(关闭在途预留):单用户闭环 200 并发 823 → 1564 RPS; s1500 成功率 70% → 100%;16 用户闭环 1355 → 1619 RPS;s1000 p99 总耗时 10.2s → 2.3s、内存 3.2GB → 1.2GB(对比改动前)。低负载无回退,对账差额为 0。 --- backend/cmd/server/wire.go | 5 + backend/cmd/server/wire_gen.go | 11 +- backend/cmd/server/wire_gen_test.go | 1 + backend/internal/repository/account_repo.go | 30 +- .../repository/usage_billing_batch_repo.go | 544 ++++++++++++++++ ...age_billing_batch_repo_integration_test.go | 467 +++++++++++++ .../internal/repository/usage_billing_repo.go | 14 +- .../internal/service/gateway_usage_billing.go | 11 +- backend/internal/service/usage_billing.go | 14 + .../internal/service/usage_billing_lane.go | 311 +++++++++ .../service/usage_billing_lane_test.go | 616 ++++++++++++++++++ backend/internal/service/wire.go | 7 + 12 files changed, 2019 insertions(+), 12 deletions(-) create mode 100644 backend/internal/repository/usage_billing_batch_repo.go create mode 100644 backend/internal/repository/usage_billing_batch_repo_integration_test.go create mode 100644 backend/internal/service/usage_billing_lane.go create mode 100644 backend/internal/service/usage_billing_lane_test.go diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go index 05c3334f13..b70b810a28 100644 --- a/backend/cmd/server/wire.go +++ b/backend/cmd/server/wire.go @@ -111,6 +111,7 @@ func provideCleanup( emailQueue *service.EmailQueueService, billingCache *service.BillingCacheService, usageRecordWorkerPool *service.UsageRecordWorkerPool, + usageBillingLanes *service.UsageBillingLaneCombiner, balanceNotify *service.BalanceNotifyService, digestSessions *service.DigestSessionStore, subscriptionService *service.SubscriptionService, @@ -331,6 +332,10 @@ func provideCleanup( } return nil }}, + {"UsageBillingLaneCombiner", func() error { + usageBillingLanes.Stop() + return nil + }}, {"OAuthService", func() error { oauth.Stop() return nil diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 1356765b79..b8d8e28973 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -105,7 +105,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { usageLogRepository := repository.NewUsageLogRepository(client, db) usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator) opsRepository := repository.NewOpsRepository(db) - usageBillingRepository := repository.NewUsageBillingRepository(client, db) + usageBillingBatchRepository := repository.NewUsageBillingRepository(client, db) + usageBillingLaneCombiner := service.NewUsageBillingLaneCombiner(usageBillingBatchRepository) + usageBillingRepository := service.ProvideUsageBillingRepository(usageBillingLaneCombiner) gatewayCache := repository.NewGatewayCache(redisClient) schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db) schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig) @@ -359,7 +361,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher) channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService) userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService) - v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) + v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, usageBillingLaneCombiner, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) application := &Application{ Server: httpServer, PromptAudit: promptService, @@ -426,6 +428,7 @@ func provideCleanup( emailQueue *service.EmailQueueService, billingCache *service.BillingCacheService, usageRecordWorkerPool *service.UsageRecordWorkerPool, + usageBillingLanes *service.UsageBillingLaneCombiner, balanceNotify *service.BalanceNotifyService, digestSessions *service.DigestSessionStore, subscriptionService *service.SubscriptionService, @@ -645,6 +648,10 @@ func provideCleanup( } return nil }}, + {"UsageBillingLaneCombiner", func() error { + usageBillingLanes.Stop() + return nil + }}, {"OAuthService", func() error { oauth.Stop() return nil diff --git a/backend/cmd/server/wire_gen_test.go b/backend/cmd/server/wire_gen_test.go index b8e601a508..4d7eb8c99d 100644 --- a/backend/cmd/server/wire_gen_test.go +++ b/backend/cmd/server/wire_gen_test.go @@ -81,6 +81,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) { emailQueueSvc, billingCacheSvc, &service.UsageRecordWorkerPool{}, + nil, // usageBillingLanes service.ProvideBalanceNotifyService(nil, nil, nil, nil), service.NewDigestSessionStore(), &service.SubscriptionService{}, diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 733ff9034b..cf0577e8ee 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1478,10 +1478,38 @@ func (r *accountRepository) BatchUpdateLastUsed(ctx context.Context, updates map caseSQL += " END, updated_at = NOW() WHERE id = ANY($" + itoa(idx) + ") AND deleted_at IS NULL" args = append(args, pq.Array(ids)) - _, err := r.sql.ExecContext(ctx, caseSQL, args...) + // 同一事务内先按 id 升序锁定目标行再更新,与计费合并事务锁多个账号行的顺序一致; + // 锁强度与更新非键列相同,不阻塞引用 accounts 的外键检查。 + exec := r.sql + var tx *sql.Tx + if db, ok := r.sql.(*sql.DB); ok { + var err error + if tx, err = db.BeginTx(ctx, nil); err != nil { + return err + } + defer func() { + if tx != nil { + _ = tx.Rollback() + } + }() + exec = tx + } + rows, err := exec.QueryContext(ctx, "SELECT id FROM accounts WHERE id = ANY($1) AND deleted_at IS NULL ORDER BY id FOR NO KEY UPDATE", pq.Array(ids)) if err != nil { return err } + if err := rows.Close(); err != nil { + return err + } + if _, err := exec.ExecContext(ctx, caseSQL, args...); err != nil { + return err + } + if tx != nil { + if err := tx.Commit(); err != nil { + return err + } + tx = nil + } lastUsedPayload := make(map[string]int64, len(updates)) for id, ts := range updates { lastUsedPayload[strconv.FormatInt(id, 10)] = ts.Unix() diff --git a/backend/internal/repository/usage_billing_batch_repo.go b/backend/internal/repository/usage_billing_batch_repo.go new file mode 100644 index 0000000000..99340f9020 --- /dev/null +++ b/backend/internal/repository/usage_billing_batch_repo.go @@ -0,0 +1,544 @@ +package repository + +import ( + "context" + "database/sql" + "errors" + "math" + "sort" + "strings" + + "github.com/lib/pq" + "github.com/shopspring/decimal" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +var ( + errUsageBillingBatchMixedUsers = errors.New("usage billing batch contains commands of different users") + errUsageBillingBatchDuplicateRequest = errors.New("usage billing batch contains duplicate request keys") + errUsageBillingBatchNilCommand = errors.New("usage billing batch contains nil command") + errUsageBillingBatchDedupRowMissing = errors.New("usage billing dedup row missing after claim conflict") + errUsageBillingBatchNonFiniteAmount = errors.New("usage billing batch contains non-finite amount") +) + +type usageBillingRequestKey struct { + requestID string + apiKeyID int64 +} + +// ApplyBatch 在一个事务内结算同一用户的多条计费命令。 +// +// 每条命令的去重认领、各项累加与返回结果都与按 cmds 顺序逐条调用 Apply 一致: +// - 认领用一条多行 INSERT,未认领的命令按已有指纹判定为重复(Applied=false)或指纹冲突; +// 认领后在归档表命中的命令同样判定,并删除本事务插入的认领行。 +// - 同一行的多次累加合并为一条语句,累加值取各命令金额之和。同一事务内 NOW() 不变, +// 窗口重置类表达式的合并结果与逐条执行相同。 +// - 逐条命令的扣费后余额、是否透支、Key 额度是否在该条耗尽、账号额度状态, +// 由合并语句返回的累加后值按命令顺序推算。 +// +// 行锁按 user_subscriptions → users → api_keys → accounts 的顺序获取,表内按主键升序, +// 与 Apply 的加锁顺序一致。 +// +// 命令校验失败(混合用户、重复请求键、缺 request_id、非有限金额)时直接返回 error。 +// 返回 error 时没有任何命令生效;提交请求发出后连接中断时提交结果未知,与 Apply 相同。 +func (r *usageBillingRepository) ApplyBatch(ctx context.Context, cmds []*service.UsageBillingCommand) (_ []service.UsageBillingBatchOutcome, err error) { + if len(cmds) == 0 { + return nil, nil + } + if r == nil || r.db == nil { + return nil, errors.New("usage billing repository db is nil") + } + + userID, err := validateUsageBillingBatch(cmds) + if err != nil { + return nil, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer func() { + if tx != nil { + _ = tx.Rollback() + } + }() + + outcomes := make([]service.UsageBillingBatchOutcome, len(cmds)) + applied, err := claimUsageBillingBatch(ctx, tx, cmds, outcomes) + if err != nil { + return nil, err + } + for i := range cmds { + if applied[i] { + outcomes[i].Result = &service.UsageBillingApplyResult{Applied: true} + } + } + + if err := applyUsageBillingBatchSubscriptions(ctx, tx, cmds, applied); err != nil { + return nil, err + } + if err := applyUsageBillingBatchBalance(ctx, tx, userID, cmds, applied, outcomes); err != nil { + return nil, err + } + if err := applyUsageBillingBatchAPIKeys(ctx, tx, cmds, applied, outcomes); err != nil { + return nil, err + } + if err := applyUsageBillingBatchAccountQuotas(ctx, tx, cmds, applied, outcomes); err != nil { + return nil, err + } + + if err := tx.Commit(); err != nil { + return nil, err + } + tx = nil + return outcomes, nil +} + +// validateUsageBillingBatch 规范化命令并校验:非空、request_id 非空、同一用户、(request_id, api_key_id) 互不相同。 +func validateUsageBillingBatch(cmds []*service.UsageBillingCommand) (int64, error) { + var userID int64 + seen := make(map[usageBillingRequestKey]struct{}, len(cmds)) + for i, cmd := range cmds { + if cmd == nil { + return 0, errUsageBillingBatchNilCommand + } + cmd.Normalize() + if cmd.RequestID == "" { + return 0, service.ErrUsageBillingRequestIDRequired + } + for _, amount := range []float64{cmd.BalanceCost, cmd.SubscriptionCost, cmd.APIKeyQuotaCost, cmd.APIKeyRateLimitCost, cmd.AccountQuotaCost} { + if math.IsNaN(amount) || math.IsInf(amount, 0) { + return 0, errUsageBillingBatchNonFiniteAmount + } + } + if i == 0 { + userID = cmd.UserID + } else if cmd.UserID != userID { + return 0, errUsageBillingBatchMixedUsers + } + key := usageBillingRequestKey{requestID: cmd.RequestID, apiKeyID: cmd.APIKeyID} + if _, dup := seen[key]; dup { + return 0, errUsageBillingBatchDuplicateRequest + } + seen[key] = struct{}{} + } + return userID, nil +} + +// claimUsageBillingBatch 认领整批命令,返回每条命令是否需要结算;不需要结算的命令在 outcomes 中写入结果。 +func claimUsageBillingBatch(ctx context.Context, tx *sql.Tx, cmds []*service.UsageBillingCommand, outcomes []service.UsageBillingBatchOutcome) ([]bool, error) { + // 插入顺序按 (api_key_id, request_id) 排序,并发事务在唯一索引上的等待顺序一致。 + order := make([]int, len(cmds)) + for i := range order { + order[i] = i + } + sort.Slice(order, func(a, b int) bool { + ca, cb := cmds[order[a]], cmds[order[b]] + if ca.APIKeyID != cb.APIKeyID { + return ca.APIKeyID < cb.APIKeyID + } + return ca.RequestID < cb.RequestID + }) + requestIDs := make([]string, len(cmds)) + apiKeyIDs := make([]int64, len(cmds)) + fingerprints := make([]string, len(cmds)) + for pos, i := range order { + requestIDs[pos] = cmds[i].RequestID + apiKeyIDs[pos] = cmds[i].APIKeyID + fingerprints[pos] = cmds[i].RequestFingerprint + } + + rows, err := tx.QueryContext(ctx, ` + INSERT INTO usage_billing_dedup (request_id, api_key_id, request_fingerprint) + SELECT t.request_id, t.api_key_id, t.request_fingerprint + FROM unnest($1::text[], $2::bigint[], $3::text[]) WITH ORDINALITY AS t(request_id, api_key_id, request_fingerprint, ord) + ORDER BY t.ord + ON CONFLICT (request_id, api_key_id) DO NOTHING + RETURNING id, request_id, api_key_id + `, pq.Array(requestIDs), pq.Array(apiKeyIDs), pq.Array(fingerprints)) + if err != nil { + return nil, err + } + claimedIDs := make(map[usageBillingRequestKey]int64, len(cmds)) + for rows.Next() { + var id int64 + var key usageBillingRequestKey + if err := rows.Scan(&id, &key.requestID, &key.apiKeyID); err != nil { + _ = rows.Close() + return nil, err + } + claimedIDs[key] = id + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, err + } + if err := rows.Close(); err != nil { + return nil, err + } + + applied := make([]bool, len(cmds)) + var conflicted, claimed []usageBillingRequestKey + for _, cmd := range cmds { + key := usageBillingRequestKey{requestID: cmd.RequestID, apiKeyID: cmd.APIKeyID} + if _, ok := claimedIDs[key]; ok { + claimed = append(claimed, key) + } else { + conflicted = append(conflicted, key) + } + } + + if len(conflicted) > 0 { + existing, err := queryUsageBillingFingerprints(ctx, tx, ` + SELECT d.request_id, d.api_key_id, d.request_fingerprint + FROM usage_billing_dedup d + JOIN unnest($1::text[], $2::bigint[]) AS t(request_id, api_key_id) + ON d.request_id = t.request_id AND d.api_key_id = t.api_key_id + `, conflicted) + if err != nil { + return nil, err + } + for i, cmd := range cmds { + key := usageBillingRequestKey{requestID: cmd.RequestID, apiKeyID: cmd.APIKeyID} + if _, ok := claimedIDs[key]; ok { + continue + } + fingerprint, ok := existing[key] + if !ok { + return nil, errUsageBillingBatchDedupRowMissing + } + outcomes[i] = usageBillingDuplicateOutcome(fingerprint, cmd.RequestFingerprint) + } + } + + var archived map[usageBillingRequestKey]string + if len(claimed) > 0 { + archived, err = queryUsageBillingFingerprints(ctx, tx, ` + SELECT a.request_id, a.api_key_id, a.request_fingerprint + FROM usage_billing_dedup_archive a + JOIN unnest($1::text[], $2::bigint[]) AS t(request_id, api_key_id) + ON a.request_id = t.request_id AND a.api_key_id = t.api_key_id + `, claimed) + if err != nil { + return nil, err + } + } + var releaseIDs []int64 + for i, cmd := range cmds { + key := usageBillingRequestKey{requestID: cmd.RequestID, apiKeyID: cmd.APIKeyID} + id, ok := claimedIDs[key] + if !ok { + continue + } + if fingerprint, hit := archived[key]; hit { + outcomes[i] = usageBillingDuplicateOutcome(fingerprint, cmd.RequestFingerprint) + releaseIDs = append(releaseIDs, id) + continue + } + applied[i] = true + } + if len(releaseIDs) > 0 { + if _, err := tx.ExecContext(ctx, `DELETE FROM usage_billing_dedup WHERE id = ANY($1::bigint[])`, pq.Array(releaseIDs)); err != nil { + return nil, err + } + } + return applied, nil +} + +// usageBillingDuplicateOutcome 按已登记的指纹判定重复命令:指纹相同为已结算(Applied=false),不同为指纹冲突。 +func usageBillingDuplicateOutcome(existingFingerprint, fingerprint string) service.UsageBillingBatchOutcome { + if strings.TrimSpace(existingFingerprint) != strings.TrimSpace(fingerprint) { + return service.UsageBillingBatchOutcome{Err: service.ErrUsageBillingRequestConflict} + } + return service.UsageBillingBatchOutcome{Result: &service.UsageBillingApplyResult{Applied: false}} +} + +func queryUsageBillingFingerprints(ctx context.Context, tx *sql.Tx, query string, keys []usageBillingRequestKey) (map[usageBillingRequestKey]string, error) { + requestIDs := make([]string, len(keys)) + apiKeyIDs := make([]int64, len(keys)) + for i, key := range keys { + requestIDs[i] = key.requestID + apiKeyIDs[i] = key.apiKeyID + } + rows, err := tx.QueryContext(ctx, query, pq.Array(requestIDs), pq.Array(apiKeyIDs)) + if err != nil { + return nil, err + } + found := make(map[usageBillingRequestKey]string, len(keys)) + for rows.Next() { + var key usageBillingRequestKey + var fingerprint string + if err := rows.Scan(&key.requestID, &key.apiKeyID, &fingerprint); err != nil { + _ = rows.Close() + return nil, err + } + found[key] = fingerprint + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, err + } + if err := rows.Close(); err != nil { + return nil, err + } + return found, nil +} + +// usageBillingAmount 把已量化到 8 位小数的金额转为精确十进制。 +func usageBillingAmount(v float64) decimal.Decimal { + return decimal.NewFromFloat(v) +} + +// usageBillingAmountGroup 汇总同一行上的多条命令:indexes 按命令顺序排列。 +type usageBillingAmountGroup struct { + sum decimal.Decimal + indexes []int +} + +func groupUsageBillingAmounts(cmds []*service.UsageBillingCommand, applied []bool, pick func(*service.UsageBillingCommand) (int64, float64, bool)) (map[int64]*usageBillingAmountGroup, []int64) { + groups := make(map[int64]*usageBillingAmountGroup) + for i, cmd := range cmds { + if !applied[i] { + continue + } + id, amount, ok := pick(cmd) + if !ok || !(amount > 0) { + continue + } + g := groups[id] + if g == nil { + g = &usageBillingAmountGroup{} + groups[id] = g + } + g.sum = g.sum.Add(usageBillingAmount(amount)) + g.indexes = append(g.indexes, i) + } + ids := make([]int64, 0, len(groups)) + for id := range groups { + ids = append(ids, id) + } + sort.Slice(ids, func(a, b int) bool { return ids[a] < ids[b] }) + return groups, ids +} + +func applyUsageBillingBatchSubscriptions(ctx context.Context, tx *sql.Tx, cmds []*service.UsageBillingCommand, applied []bool) error { + groups, ids := groupUsageBillingAmounts(cmds, applied, func(cmd *service.UsageBillingCommand) (int64, float64, bool) { + if cmd.SubscriptionID == nil { + return 0, 0, false + } + return *cmd.SubscriptionID, cmd.SubscriptionCost, true + }) + for _, id := range ids { + if err := incrementUsageBillingSubscription(ctx, tx, id, groups[id].sum.InexactFloat64()); err != nil { + return err + } + } + return nil +} + +func applyUsageBillingBatchBalance(ctx context.Context, tx *sql.Tx, userID int64, cmds []*service.UsageBillingCommand, applied []bool, outcomes []service.UsageBillingBatchOutcome) error { + groups, _ := groupUsageBillingAmounts(cmds, applied, func(cmd *service.UsageBillingCommand) (int64, float64, bool) { + return userID, cmd.BalanceCost, true + }) + group := groups[userID] + if group == nil { + return nil + } + + var newBalance decimal.Decimal + err := tx.QueryRowContext(ctx, ` + UPDATE users + SET balance = balance - $1, + updated_at = NOW() + WHERE id = $2 AND deleted_at IS NULL + RETURNING balance + `, group.sum, userID).Scan(&newBalance) + if errors.Is(err, sql.ErrNoRows) { + return service.ErrUserNotFound + } + if err != nil { + return err + } + + running := newBalance.Add(group.sum) + for _, i := range group.indexes { + cost := usageBillingAmount(cmds[i].BalanceCost) + sufficient := running.GreaterThanOrEqual(cost) + running = running.Sub(cost) + balance := running.InexactFloat64() + outcomes[i].Result.NewBalance = &balance + outcomes[i].Result.BalanceOverdrafted = !sufficient + } + return nil +} + +func applyUsageBillingBatchAPIKeys(ctx context.Context, tx *sql.Tx, cmds []*service.UsageBillingCommand, applied []bool, outcomes []service.UsageBillingBatchOutcome) error { + quotaGroups, quotaIDs := groupUsageBillingAmounts(cmds, applied, func(cmd *service.UsageBillingCommand) (int64, float64, bool) { + return cmd.APIKeyID, cmd.APIKeyQuotaCost, true + }) + rateGroups, rateIDs := groupUsageBillingAmounts(cmds, applied, func(cmd *service.UsageBillingCommand) (int64, float64, bool) { + return cmd.APIKeyID, cmd.APIKeyRateLimitCost, true + }) + + ids := mergeSortedIDs(quotaIDs, rateIDs) + for _, id := range ids { + if group := quotaGroups[id]; group != nil { + if err := applyUsageBillingBatchAPIKeyQuota(ctx, tx, id, group, cmds, outcomes); err != nil { + return err + } + } + if group := rateGroups[id]; group != nil { + err := incrementUsageBillingAPIKeyRateLimit(ctx, tx, id, group.sum.InexactFloat64()) + if err != nil && !errors.Is(err, service.ErrAPIKeyNotFound) { + return err + } + } + } + return nil +} + +func applyUsageBillingBatchAPIKeyQuota(ctx context.Context, tx *sql.Tx, apiKeyID int64, group *usageBillingAmountGroup, cmds []*service.UsageBillingCommand, outcomes []service.UsageBillingBatchOutcome) error { + var quota, used decimal.Decimal + err := tx.QueryRowContext(ctx, usageBillingAPIKeyQuotaUpdate+` + RETURNING quota, quota_used + `, group.sum, apiKeyID, service.StatusAPIKeyActive, service.StatusAPIKeyQuotaExhausted).Scan("a, &used) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + if !quota.IsPositive() { + return nil + } + running := used.Sub(group.sum) + for _, i := range group.indexes { + before := running + running = running.Add(usageBillingAmount(cmds[i].APIKeyQuotaCost)) + if running.GreaterThanOrEqual(quota) && before.LessThan(quota) { + outcomes[i].Result.APIKeyQuotaExhausted = true + } + } + return nil +} + +func applyUsageBillingBatchAccountQuotas(ctx context.Context, tx *sql.Tx, cmds []*service.UsageBillingCommand, applied []bool, outcomes []service.UsageBillingBatchOutcome) error { + groups, ids := groupUsageBillingAmounts(cmds, applied, func(cmd *service.UsageBillingCommand) (int64, float64, bool) { + return cmd.AccountID, cmd.AccountQuotaCost, service.AccountTypeSupportsQuota(cmd.AccountType) + }) + query := accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)] + for _, id := range ids { + group := groups[id] + state, err := queryAccountQuotaIncrementDecimal(ctx, tx, query, id, group.sum) + if err != nil { + return err + } + if state == nil { + continue + } + if state.crossed(group.sum) { + accountID := id + if err := enqueueSchedulerOutbox(ctx, tx, service.SchedulerOutboxEventAccountChanged, &accountID, nil, nil); err != nil { + logger.LegacyPrintf("repository.usage_billing", "[SchedulerOutbox] enqueue quota exceeded failed: account=%d err=%v", accountID, err) + return err + } + } + + // 日/周维度只在库中设置了对应上限时累加,未累加的维度各条命令看到的都是语句返回值。 + total := state.totalUsed.Sub(group.sum) + daily := state.dailyUsed + if state.dailyLimit.IsPositive() { + daily = daily.Sub(group.sum) + } + weekly := state.weeklyUsed + if state.weeklyLimit.IsPositive() { + weekly = weekly.Sub(group.sum) + } + for _, i := range group.indexes { + cost := usageBillingAmount(cmds[i].AccountQuotaCost) + total = total.Add(cost) + if state.dailyLimit.IsPositive() { + daily = daily.Add(cost) + } + if state.weeklyLimit.IsPositive() { + weekly = weekly.Add(cost) + } + outcomes[i].Result.QuotaState = &service.AccountQuotaState{ + TotalUsed: total.InexactFloat64(), + TotalLimit: state.totalLimit.InexactFloat64(), + DailyUsed: daily.InexactFloat64(), + DailyLimit: state.dailyLimit.InexactFloat64(), + WeeklyUsed: weekly.InexactFloat64(), + WeeklyLimit: state.weeklyLimit.InexactFloat64(), + } + } + } + return nil +} + +// accountQuotaDecimalState 是账号配额累加语句返回的累加后状态(精确十进制)。 +type accountQuotaDecimalState struct { + totalUsed, totalLimit decimal.Decimal + dailyUsed, dailyLimit decimal.Decimal + weeklyUsed, weeklyLimit decimal.Decimal +} + +// crossed 判断本次累加 amount 是否让任一设置了上限的维度从未超跨到已超。 +func (s *accountQuotaDecimalState) crossed(amount decimal.Decimal) bool { + cross := func(used, limit decimal.Decimal) bool { + return limit.IsPositive() && used.GreaterThanOrEqual(limit) && used.Sub(amount).LessThan(limit) + } + return cross(s.totalUsed, s.totalLimit) || cross(s.dailyUsed, s.dailyLimit) || cross(s.weeklyUsed, s.weeklyLimit) +} + +// queryAccountQuotaIncrementDecimal 执行一条账号配额累加语句,未命中任何行时返回 nil 状态。 +func queryAccountQuotaIncrementDecimal(ctx context.Context, tx *sql.Tx, query string, accountID int64, amount decimal.Decimal) (*accountQuotaDecimalState, error) { + rows, err := tx.QueryContext(ctx, query, amount, accountID) + if err != nil { + return nil, err + } + var state *accountQuotaDecimalState + if rows.Next() { + state = &accountQuotaDecimalState{} + if err := rows.Scan( + &state.totalUsed, &state.totalLimit, + &state.dailyUsed, &state.dailyLimit, + &state.weeklyUsed, &state.weeklyLimit, + ); err != nil { + _ = rows.Close() + return nil, err + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, err + } + if err := rows.Close(); err != nil { + return nil, err + } + return state, nil +} + +// mergeSortedIDs 合并两个升序 id 列表并去重。 +func mergeSortedIDs(a, b []int64) []int64 { + out := make([]int64, 0, len(a)+len(b)) + i, j := 0, 0 + for i < len(a) || j < len(b) { + switch { + case j >= len(b) || (i < len(a) && a[i] < b[j]): + out = append(out, a[i]) + i++ + case i >= len(a) || b[j] < a[i]: + out = append(out, b[j]) + j++ + default: + out = append(out, a[i]) + i++ + j++ + } + } + return out +} diff --git a/backend/internal/repository/usage_billing_batch_repo_integration_test.go b/backend/internal/repository/usage_billing_batch_repo_integration_test.go new file mode 100644 index 0000000000..d1907acaff --- /dev/null +++ b/backend/internal/repository/usage_billing_batch_repo_integration_test.go @@ -0,0 +1,467 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "fmt" + "math" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// batchBillingFixture 是一个用户及其计费相关的行:两个 Key(A 有额度)、两个支持额度的账号 +// (P 设总额度与日额度,Q 只设周额度)和一个订阅。 +type batchBillingFixture struct { + userID int64 + keyA, keyB int64 + accountP int64 + accountQ int64 + subscriptionID int64 +} + +func newBatchBillingFixture(t *testing.T, client *dbent.Client, balance float64) batchBillingFixture { + t.Helper() + suffix := uuid.NewString() + user := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("usage-billing-batch-%s@example.com", suffix), + PasswordHash: "hash", + Balance: balance, + }) + group := mustCreateGroup(t, client, &service.Group{ + Name: "usage-billing-batch-group-" + suffix, + Platform: service.PlatformAnthropic, + SubscriptionType: service.SubscriptionTypeSubscription, + }) + keyA := mustCreateApiKey(t, client, &service.APIKey{ + UserID: user.ID, Key: "sk-usage-billing-batch-a-" + suffix, Name: "batch-a", Quota: 5, + }) + keyB := mustCreateApiKey(t, client, &service.APIKey{ + UserID: user.ID, Key: "sk-usage-billing-batch-b-" + suffix, Name: "batch-b", + }) + accountP := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-batch-p-" + suffix, + Type: service.AccountTypeAPIKey, + Extra: map[string]any{"quota_limit": 6.0, "quota_daily_limit": 4.0}, + }) + accountQ := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-batch-q-" + suffix, + Type: service.AccountTypeAPIKey, + Extra: map[string]any{"quota_weekly_limit": 3.0}, + }) + subscription := mustCreateSubscription(t, client, &service.UserSubscription{UserID: user.ID, GroupID: group.ID}) + return batchBillingFixture{ + userID: user.ID, keyA: keyA.ID, keyB: keyB.ID, + accountP: accountP.ID, accountQ: accountQ.ID, subscriptionID: subscription.ID, + } +} + +// batchBillingScript 描述一组命令;key/account 用 'A'/'B'、'P'/'Q' 指代夹具中的行。 +type batchBillingStep struct { + key byte + account byte + balance float64 + subscription float64 + keyQuota float64 + keyRate float64 + accountQuota float64 +} + +func (f batchBillingFixture) commands(prefix string, steps []batchBillingStep) []*service.UsageBillingCommand { + cmds := make([]*service.UsageBillingCommand, len(steps)) + for i, s := range steps { + cmd := &service.UsageBillingCommand{ + RequestID: fmt.Sprintf("%s-%d", prefix, i), + UserID: f.userID, + AccountType: service.AccountTypeAPIKey, + BalanceCost: s.balance, + APIKeyQuotaCost: s.keyQuota, + APIKeyRateLimitCost: s.keyRate, + AccountQuotaCost: s.accountQuota, + } + cmd.APIKeyID = f.keyA + if s.key == 'B' { + cmd.APIKeyID = f.keyB + } + cmd.AccountID = f.accountP + if s.account == 'Q' { + cmd.AccountID = f.accountQ + } + if s.subscription > 0 { + subscriptionID := f.subscriptionID + cmd.SubscriptionID = &subscriptionID + cmd.SubscriptionCost = s.subscription + } + cmds[i] = cmd + } + return cmds +} + +type batchBillingState struct { + balance string + keyAUsed, keyAStatus string + keyAUsage5h, keyAUsage1d string + keyBUsage5h, keyBUsage7d string + pUsed, pDailyUsed, pWeeklyUsed string + qUsed, qDailyUsed, qWeeklyUsed string + subDaily, subWeekly, subMonth string + dedupRows int + pOutbox, qOutbox int +} + +func readBatchBillingState(t *testing.T, ctx context.Context, f batchBillingFixture) batchBillingState { + t.Helper() + var s batchBillingState + q := func(dst any, query string, args ...any) { + require.NoError(t, integrationDB.QueryRowContext(ctx, query, args...).Scan(dst)) + } + q(&s.balance, "SELECT balance::text FROM users WHERE id = $1", f.userID) + q(&s.keyAUsed, "SELECT quota_used::text FROM api_keys WHERE id = $1", f.keyA) + q(&s.keyAStatus, "SELECT status FROM api_keys WHERE id = $1", f.keyA) + q(&s.keyAUsage5h, "SELECT usage_5h::text FROM api_keys WHERE id = $1", f.keyA) + q(&s.keyAUsage1d, "SELECT usage_1d::text FROM api_keys WHERE id = $1", f.keyA) + q(&s.keyBUsage5h, "SELECT usage_5h::text FROM api_keys WHERE id = $1", f.keyB) + q(&s.keyBUsage7d, "SELECT usage_7d::text FROM api_keys WHERE id = $1", f.keyB) + accountUsed := func(id int64, field string) string { + var v string + q(&v, "SELECT COALESCE((extra->>$2)::numeric, 0)::text FROM accounts WHERE id = $1", id, field) + return v + } + s.pUsed, s.pDailyUsed, s.pWeeklyUsed = accountUsed(f.accountP, "quota_used"), accountUsed(f.accountP, "quota_daily_used"), accountUsed(f.accountP, "quota_weekly_used") + s.qUsed, s.qDailyUsed, s.qWeeklyUsed = accountUsed(f.accountQ, "quota_used"), accountUsed(f.accountQ, "quota_daily_used"), accountUsed(f.accountQ, "quota_weekly_used") + q(&s.subDaily, "SELECT daily_usage_usd::text FROM user_subscriptions WHERE id = $1", f.subscriptionID) + q(&s.subWeekly, "SELECT weekly_usage_usd::text FROM user_subscriptions WHERE id = $1", f.subscriptionID) + q(&s.subMonth, "SELECT monthly_usage_usd::text FROM user_subscriptions WHERE id = $1", f.subscriptionID) + q(&s.dedupRows, "SELECT COUNT(*) FROM usage_billing_dedup WHERE api_key_id IN ($1, $2)", f.keyA, f.keyB) + q(&s.pOutbox, "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", service.SchedulerOutboxEventAccountChanged, f.accountP) + q(&s.qOutbox, "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", service.SchedulerOutboxEventAccountChanged, f.accountQ) + return s +} + +func TestUsageBillingRepositoryApplyBatch_MatchesSequentialApply(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + + // 余额 10:第 6 条起透支;Key A 额度 5 在第 5 条耗尽;账号 P 日额度 4 在第 5 条、总额度 6 在第 6 条越线; + // 账号 Q 周额度 3 在第 3 条恰好达到;第 4 条走订阅。 + steps := []batchBillingStep{ + {key: 'A', account: 'P', balance: 1.5, keyQuota: 1.5, keyRate: 1.5, accountQuota: 1.5}, + {key: 'A', account: 'P', balance: 2.25, keyQuota: 2.25, keyRate: 2.25, accountQuota: 2.25}, + {key: 'B', account: 'Q', balance: 3, keyRate: 3, accountQuota: 3}, + {key: 'A', account: 'P', subscription: 1, keyQuota: 1}, + {key: 'A', account: 'P', balance: 4, keyQuota: 0.5, accountQuota: 0.5}, + {key: 'B', account: 'P', balance: 0.75, keyRate: 0.12345678, accountQuota: 2}, + {key: 'A', account: 'Q', balance: 0.1, keyQuota: 0.3, accountQuota: 0.00000001}, + {key: 'B', account: 'Q', balance: 0.00000003, keyRate: 0.1}, + } + + sequential := newBatchBillingFixture(t, client, 10) + batched := newBatchBillingFixture(t, client, 10) + + seqCmds := sequential.commands("seq-"+uuid.NewString(), steps) + seqResults := make([]*service.UsageBillingApplyResult, len(seqCmds)) + for i, cmd := range seqCmds { + res, err := repo.Apply(ctx, cmd) + require.NoError(t, err, "sequential step %d", i) + seqResults[i] = res + } + + outcomes, err := repo.ApplyBatch(ctx, batched.commands("batch-"+uuid.NewString(), steps)) + require.NoError(t, err) + require.Len(t, outcomes, len(steps)) + + for i := range steps { + require.NoError(t, outcomes[i].Err, "step %d", i) + require.Equal(t, seqResults[i], outcomes[i].Result, "step %d", i) + } + + seqState := readBatchBillingState(t, ctx, sequential) + batchState := readBatchBillingState(t, ctx, batched) + // 逐条结算时每次越线各写一条 outbox,合并结算每个账号至多一条;两边都必须至少写一条。 + require.Positive(t, seqState.pOutbox) + require.Positive(t, batchState.pOutbox) + require.Positive(t, seqState.qOutbox) + require.Positive(t, batchState.qOutbox) + require.Equal(t, 1, batchState.pOutbox) + require.Equal(t, 1, batchState.qOutbox) + seqState.pOutbox, seqState.qOutbox, batchState.pOutbox, batchState.qOutbox = 0, 0, 0, 0 + require.Equal(t, seqState, batchState) + require.Equal(t, len(steps), batchState.dedupRows) + require.Equal(t, service.StatusAPIKeyQuotaExhausted, batchState.keyAStatus) +} + +func TestUsageBillingRepositoryApplyBatch_DuplicateAndConflictingRequests(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + f := newBatchBillingFixture(t, client, 10) + + prefix := "dup-" + uuid.NewString() + settled := f.commands(prefix+"-settled", []batchBillingStep{{key: 'B', balance: 1}})[0] + conflicted := f.commands(prefix+"-conflicted", []batchBillingStep{{key: 'B', balance: 2}})[0] + for _, cmd := range []*service.UsageBillingCommand{settled, conflicted} { + res, err := repo.Apply(ctx, cmd) + require.NoError(t, err) + require.True(t, res.Applied) + } + + retry := f.commands(prefix+"-settled", []batchBillingStep{{key: 'B', balance: 1}})[0] + changed := f.commands(prefix+"-conflicted", []batchBillingStep{{key: 'B', balance: 2.5}})[0] + fresh := f.commands(prefix+"-fresh", []batchBillingStep{{key: 'B', balance: 0.5}})[0] + + outcomes, err := repo.ApplyBatch(ctx, []*service.UsageBillingCommand{retry, changed, fresh}) + require.NoError(t, err) + require.NoError(t, outcomes[0].Err) + require.False(t, outcomes[0].Result.Applied) + require.ErrorIs(t, outcomes[1].Err, service.ErrUsageBillingRequestConflict) + require.Nil(t, outcomes[1].Result) + require.NoError(t, outcomes[2].Err) + require.True(t, outcomes[2].Result.Applied) + require.InDelta(t, 6.5, *outcomes[2].Result.NewBalance, 1e-9) + + state := readBatchBillingState(t, ctx, f) + require.Equal(t, "6.50000000", state.balance) + require.Equal(t, 3, state.dedupRows) +} + +func TestUsageBillingRepositoryApplyBatch_ArchivedRequestsAreNotReapplied(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + f := newBatchBillingFixture(t, client, 10) + + prefix := "archived-" + uuid.NewString() + archived := f.commands(prefix+"-same", []batchBillingStep{{key: 'B', balance: 1}})[0] + archivedChanged := f.commands(prefix+"-changed", []batchBillingStep{{key: 'B', balance: 2}})[0] + fresh := f.commands(prefix+"-fresh", []batchBillingStep{{key: 'B', balance: 3}})[0] + for _, cmd := range []*service.UsageBillingCommand{archived, archivedChanged, fresh} { + cmd.Normalize() + } + _, err := integrationDB.ExecContext(ctx, ` + INSERT INTO usage_billing_dedup_archive (request_id, api_key_id, request_fingerprint, created_at) + VALUES ($1, $2, $3, NOW()), ($4, $5, $6, NOW()) + `, archived.RequestID, archived.APIKeyID, archived.RequestFingerprint, + archivedChanged.RequestID, archivedChanged.APIKeyID, "different-fingerprint") + require.NoError(t, err) + + outcomes, err := repo.ApplyBatch(ctx, []*service.UsageBillingCommand{archived, archivedChanged, fresh}) + require.NoError(t, err) + require.NoError(t, outcomes[0].Err) + require.False(t, outcomes[0].Result.Applied) + require.ErrorIs(t, outcomes[1].Err, service.ErrUsageBillingRequestConflict) + require.True(t, outcomes[2].Result.Applied) + + state := readBatchBillingState(t, ctx, f) + require.Equal(t, "7.00000000", state.balance) + require.Equal(t, 1, state.dedupRows, "claims of archived requests must not remain") +} + +func TestUsageBillingRepositoryApplyBatch_RollsBackWholeBatchOnError(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + + t.Run("deleted user", func(t *testing.T) { + f := newBatchBillingFixture(t, client, 10) + _, err := integrationDB.ExecContext(ctx, "UPDATE users SET deleted_at = NOW() WHERE id = $1", f.userID) + require.NoError(t, err) + + _, err = repo.ApplyBatch(ctx, f.commands("deleted-user-"+uuid.NewString(), []batchBillingStep{ + {key: 'A', account: 'P', balance: 1, keyQuota: 1, accountQuota: 1}, + {key: 'B', balance: 1}, + })) + require.ErrorIs(t, err, service.ErrUserNotFound) + state := readBatchBillingState(t, ctx, f) + require.Zero(t, state.dedupRows) + require.Equal(t, "0", state.pUsed) + }) + + t.Run("missing subscription", func(t *testing.T) { + f := newBatchBillingFixture(t, client, 10) + _, err := integrationDB.ExecContext(ctx, "UPDATE user_subscriptions SET deleted_at = NOW() WHERE id = $1", f.subscriptionID) + require.NoError(t, err) + + _, err = repo.ApplyBatch(ctx, f.commands("missing-sub-"+uuid.NewString(), []batchBillingStep{ + {key: 'B', balance: 1}, + {key: 'A', subscription: 1}, + })) + require.ErrorIs(t, err, service.ErrSubscriptionNotFound) + state := readBatchBillingState(t, ctx, f) + require.Zero(t, state.dedupRows) + require.Equal(t, "10.00000000", state.balance) + }) + + t.Run("invalid batches", func(t *testing.T) { + f := newBatchBillingFixture(t, client, 10) + other := newBatchBillingFixture(t, client, 10) + prefix := "invalid-" + uuid.NewString() + + mixed := append(f.commands(prefix+"-f", []batchBillingStep{{key: 'B', balance: 1}}), + other.commands(prefix+"-o", []batchBillingStep{{key: 'B', balance: 1}})...) + _, err := repo.ApplyBatch(ctx, mixed) + require.ErrorIs(t, err, errUsageBillingBatchMixedUsers) + + dup := f.commands(prefix+"-dup", []batchBillingStep{{key: 'B', balance: 1}}) + dup = append(dup, f.commands(prefix+"-dup", []batchBillingStep{{key: 'B', balance: 1}})...) + _, err = repo.ApplyBatch(ctx, dup) + require.ErrorIs(t, err, errUsageBillingBatchDuplicateRequest) + + require.Zero(t, readBatchBillingState(t, ctx, f).dedupRows) + require.Zero(t, readBatchBillingState(t, ctx, other).dedupRows) + }) +} + +func TestUsageBillingLaneCombiner_ConcurrentRequestsOfOneUser(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + lanes := service.NewUsageBillingLaneCombiner(repo) + defer lanes.Stop() + + const n = 300 + f := newBatchBillingFixture(t, client, 1000) + cmds := f.commands("lane-"+uuid.NewString(), func() []batchBillingStep { + steps := make([]batchBillingStep, n) + for i := range steps { + steps[i] = batchBillingStep{key: 'B', account: 'P', balance: float64(i%7+1) * 0.01, keyRate: 0.01, accountQuota: 0.001} + } + return steps + }()) + + results := make([]*service.UsageBillingApplyResult, n) + errs := make([]error, n) + var wg sync.WaitGroup + start := make(chan struct{}) + for i, cmd := range cmds { + wg.Add(1) + go func(i int, cmd *service.UsageBillingCommand) { + defer wg.Done() + <-start + callCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + results[i], errs[i] = lanes.Apply(callCtx, cmd) + }(i, cmd) + } + close(start) + wg.Wait() + + var total float64 + seen := make(map[string]struct{}, n) + for i := range cmds { + require.NoError(t, errs[i], "request %d", i) + require.True(t, results[i].Applied, "request %d", i) + require.False(t, results[i].BalanceOverdrafted) + key := fmt.Sprintf("%.8f", *results[i].NewBalance) + _, dup := seen[key] + require.False(t, dup, "two requests observed the same post-deduction balance %s", key) + seen[key] = struct{}{} + total += cmds[i].BalanceCost + } + + var balance float64 + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT balance FROM users WHERE id = $1", f.userID).Scan(&balance)) + require.InDelta(t, 1000-total, balance, 1e-6) + state := readBatchBillingState(t, ctx, f) + require.Equal(t, n, state.dedupRows) + require.Equal(t, "0.300", state.pUsed) + + stats := lanes.Stats() + t.Logf("lane stats: %+v", stats) + require.Positive(t, stats.Batches, "concurrent requests of one user should be merged") + require.Equal(t, uint64(n), stats.SingleApplies+stats.BatchedCommands) + require.Zero(t, stats.BatchFallbacks) +} + +func TestUsageBillingRepositoryApplyBatch_RejectsNonFiniteAmounts(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + f := newBatchBillingFixture(t, client, 10) + + cmds := f.commands("nonfinite-"+uuid.NewString(), []batchBillingStep{ + {key: 'B', balance: 1}, + {key: 'B', account: 'P', balance: 1, accountQuota: 1}, + }) + cmds[1].AccountQuotaCost = math.NaN() + + require.NotPanics(t, func() { + _, err := repo.ApplyBatch(ctx, cmds) + require.ErrorIs(t, err, errUsageBillingBatchNonFiniteAmount) + }) + require.Zero(t, readBatchBillingState(t, ctx, f).dedupRows) +} + +// 计费合并事务按 id 升序持有多个账号行锁;BatchUpdateLastUsed 也按 id 升序加锁,两者交错时不形成死锁。 +func TestAccountRepositoryBatchUpdateLastUsed_LocksRowsInIDOrder(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + accounts := newAccountRepositoryWithSQL(client, integrationDB, nil) + + low := mustCreateAccount(t, client, &service.Account{Name: "last-used-order-low-" + uuid.NewString(), Type: service.AccountTypeAPIKey}) + high := mustCreateAccount(t, client, &service.Account{Name: "last-used-order-high-" + uuid.NewString(), Type: service.AccountTypeAPIKey}) + require.Less(t, low.ID, high.ID) + _, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET temp_unschedulable_until = NOW() + INTERVAL '1 hour' WHERE id = $1", high.ID) + require.NoError(t, err) + + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + _, err = tx.ExecContext(ctx, "UPDATE accounts SET updated_at = NOW() WHERE id = $1", low.ID) + require.NoError(t, err) + + now := time.Now() + flushed := make(chan error, 1) + go func() { + flushed <- accounts.BatchUpdateLastUsed(ctx, map[int64]time.Time{low.ID: now, high.ID: now}) + }() + time.Sleep(300 * time.Millisecond) + + lockCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + _, err = tx.ExecContext(lockCtx, "UPDATE accounts SET updated_at = NOW() WHERE id = $1", high.ID) + require.NoError(t, err, "the flush must not hold the higher-id row while waiting for the lower-id row") + require.NoError(t, tx.Commit()) + + select { + case err := <-flushed: + require.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("BatchUpdateLastUsed did not finish") + } + var lastUsed sql.NullTime + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT last_used_at FROM accounts WHERE id = $1", high.ID).Scan(&lastUsed)) + require.True(t, lastUsed.Valid) +} + +func TestAccountRepositoryBatchUpdateLastUsed_DoesNotBlockForeignKeyShareLocks(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + accounts := newAccountRepositoryWithSQL(client, integrationDB, nil) + + acc := mustCreateAccount(t, client, &service.Account{Name: "last-used-fk-" + uuid.NewString(), Type: service.AccountTypeAPIKey}) + + // 外键检查对被引用行加 FOR KEY SHARE。 + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + _, err = tx.ExecContext(ctx, "SELECT id FROM accounts WHERE id = $1 FOR KEY SHARE", acc.ID) + require.NoError(t, err) + + flushCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + require.NoError(t, accounts.BatchUpdateLastUsed(flushCtx, map[int64]time.Time{acc.ID: time.Now()})) + require.NoError(t, tx.Commit()) + + var lastUsed sql.NullTime + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT last_used_at FROM accounts WHERE id = $1", acc.ID).Scan(&lastUsed)) + require.True(t, lastUsed.Valid) +} diff --git a/backend/internal/repository/usage_billing_repo.go b/backend/internal/repository/usage_billing_repo.go index 6b509215b3..e7cc6ea847 100644 --- a/backend/internal/repository/usage_billing_repo.go +++ b/backend/internal/repository/usage_billing_repo.go @@ -15,7 +15,7 @@ type usageBillingRepository struct { db *sql.DB } -func NewUsageBillingRepository(_ *dbent.Client, sqlDB *sql.DB) service.UsageBillingRepository { +func NewUsageBillingRepository(_ *dbent.Client, sqlDB *sql.DB) service.UsageBillingBatchRepository { return &usageBillingRepository{db: sqlDB} } @@ -415,9 +415,9 @@ func userExistsForBilling(ctx context.Context, tx *sql.Tx, userID int64) (bool, return true, nil } -func incrementUsageBillingAPIKeyQuota(ctx context.Context, tx *sql.Tx, apiKeyID int64, amount float64) (bool, error) { - var exhausted bool - err := tx.QueryRowContext(ctx, ` +// usageBillingAPIKeyQuotaUpdate 累加 Key 已用额度($1),本次累加从未达额度跨到达到额度时把 active 状态置为额度耗尽。 +// 参数:$1=金额 $2=api_key_id $3=active 状态 $4=额度耗尽状态。 +const usageBillingAPIKeyQuotaUpdate = ` UPDATE api_keys SET quota_used = quota_used + $1, status = CASE @@ -429,7 +429,11 @@ func incrementUsageBillingAPIKeyQuota(ctx context.Context, tx *sql.Tx, apiKeyID ELSE status END, updated_at = NOW() - WHERE id = $2 AND deleted_at IS NULL + WHERE id = $2 AND deleted_at IS NULL` + +func incrementUsageBillingAPIKeyQuota(ctx context.Context, tx *sql.Tx, apiKeyID int64, amount float64) (bool, error) { + var exhausted bool + err := tx.QueryRowContext(ctx, usageBillingAPIKeyQuotaUpdate+` RETURNING quota > 0 AND quota_used >= quota AND quota_used - $1 < quota `, amount, apiKeyID, service.StatusAPIKeyActive, service.StatusAPIKeyQuotaExhausted).Scan(&exhausted) if errors.Is(err, sql.ErrNoRows) { diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 10e0992c9c..df9afdb525 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -370,10 +370,9 @@ func applyUsageBilling(ctx context.Context, requestID string, usageLog *UsageLog return true, nil } - billingCtx, cancel := detachedBillingContext(ctx) - defer cancel() - - result, err := repo.Apply(billingCtx, cmd) + applyCtx, cancelApply := detachedBillingContext(ctx) + result, err := repo.Apply(applyCtx, cmd) + cancelApply() if err != nil { return false, err } @@ -383,6 +382,10 @@ func applyUsageBilling(ctx context.Context, requestID string, usageLog *UsageLog return false, nil } + // Apply 可能在按用户合并的结算通道中排队,结算后的缓存同步使用独立的超时。 + billingCtx, cancel := detachedBillingContext(ctx) + defer cancel() + if result.APIKeyQuotaExhausted { if invalidator, ok := p.APIKeyService.(apiKeyAuthCacheInvalidator); ok && p.APIKey != nil && p.APIKey.Key != "" { invalidator.InvalidateAuthCacheByKey(billingCtx, p.APIKey.Key) diff --git a/backend/internal/service/usage_billing.go b/backend/internal/service/usage_billing.go index 447260ecb4..fe2b374dd5 100644 --- a/backend/internal/service/usage_billing.go +++ b/backend/internal/service/usage_billing.go @@ -229,3 +229,17 @@ type UsageBillingRepository interface { CaptureBatchImageBalance(ctx context.Context, cmd *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) ReleaseBatchImageBalance(ctx context.Context, cmd *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) } + +// UsageBillingBatchOutcome 是合并结算中单条命令的结果:Err 非空时 Result 为 nil。 +type UsageBillingBatchOutcome struct { + Result *UsageBillingApplyResult + Err error +} + +// UsageBillingBatchRepository 在 UsageBillingRepository 之上支持把同一用户的多条命令合并到一个事务内结算。 +type UsageBillingBatchRepository interface { + UsageBillingRepository + // ApplyBatch 在一个事务内结算同一用户的多条命令,各条结果与按 cmds 顺序逐条调用 Apply 一致, + // 返回值与 cmds 一一对应。返回 error 时没有任何命令生效;提交请求发出后连接中断时提交结果未知,与 Apply 相同。 + ApplyBatch(ctx context.Context, cmds []*UsageBillingCommand) ([]UsageBillingBatchOutcome, error) +} diff --git a/backend/internal/service/usage_billing_lane.go b/backend/internal/service/usage_billing_lane.go new file mode 100644 index 0000000000..39a10a7dba --- /dev/null +++ b/backend/internal/service/usage_billing_lane.go @@ -0,0 +1,311 @@ +package service + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" +) + +const ( + usageBillingLaneShardCount = 64 + // usageBillingLaneMaxBatchSize 是单个合并事务最多包含的命令数。 + usageBillingLaneMaxBatchSize = 128 + usageBillingLaneFallbackLogInterval = time.Minute +) + +var errUsageBillingLaneBatchOutcomeMismatch = errors.New("usage billing batch outcome count mismatch") + +// UsageBillingLaneCombiner 是按用户合并计费事务的 UsageBillingRepository。 +// +// 每个用户一条通道:通道空闲时命令立即按单条 Apply 结算;结算进行中到达的命令排队, +// 上一轮结束后整批(至多 maxBatch 条)交给 ApplyBatch 在一个事务内结算。每个调用方阻塞等待 +// 并拿到自己那条命令的结果。ApplyBatch 返回 error 时整批逐条 Apply。 +// 每次结算(单条、整批、整批回退后的逐条)的超时从开始结算时计算,排队时间不计入。 +// +// 批量生图的冻结/结算/释放直接调用底层仓储。 +// 通道只在本进程内合并同一用户的计费;结算的原子性与幂等性由底层仓储的事务提供。 +type UsageBillingLaneCombiner struct { + repo UsageBillingBatchRepository + maxBatch int + + shards [usageBillingLaneShardCount]usageBillingLaneShard + wg sync.WaitGroup + + singleApplies atomic.Uint64 + batches atomic.Uint64 + batchedCommands atomic.Uint64 + batchFallbacks atomic.Uint64 + maxBatchSeen atomic.Uint64 + lastFallbackLog atomic.Int64 +} + +// usageBillingLaneShard 保护一组用户的通道。通道在 lanes 中存在当且仅当它的结算 goroutine 在运行。 +type usageBillingLaneShard struct { + mu sync.Mutex + lanes map[int64]*usageBillingLane + closed bool +} + +type usageBillingLane struct { + pending []*usageBillingLaneRequest +} + +type usageBillingLaneRequest struct { + ctx context.Context + cmd *UsageBillingCommand + done chan UsageBillingBatchOutcome + delivered bool +} + +// UsageBillingLaneStats 是通道合并器的累计计数。 +type UsageBillingLaneStats struct { + SingleApplies uint64 + Batches uint64 + BatchedCommands uint64 + BatchFallbacks uint64 + MaxBatchSize uint64 +} + +// NewUsageBillingLaneCombiner 创建通道合并器。 +func NewUsageBillingLaneCombiner(repo UsageBillingBatchRepository) *UsageBillingLaneCombiner { + return newUsageBillingLaneCombiner(repo, usageBillingLaneMaxBatchSize) +} + +func newUsageBillingLaneCombiner(repo UsageBillingBatchRepository, maxBatch int) *UsageBillingLaneCombiner { + c := &UsageBillingLaneCombiner{repo: repo, maxBatch: maxBatch} + for i := range c.shards { + c.shards[i].lanes = make(map[int64]*usageBillingLane) + } + return c +} + +// Apply 结算一条计费命令:进入该用户的通道并等待结果,结果与直接调用底层 Apply 一致。 +// 缺少 request_id 的命令与 Stop 之后的命令直接调用底层 Apply。 +func (c *UsageBillingLaneCombiner) Apply(ctx context.Context, cmd *UsageBillingCommand) (*UsageBillingApplyResult, error) { + if cmd == nil { + return c.repo.Apply(ctx, cmd) + } + cmd.Normalize() + if cmd.RequestID == "" { + return c.repo.Apply(ctx, cmd) + } + if ctx == nil { + ctx = context.Background() + } + req := &usageBillingLaneRequest{ctx: ctx, cmd: cmd, done: make(chan UsageBillingBatchOutcome, 1)} + if !c.enqueue(req) { + return c.repo.Apply(ctx, cmd) + } + // 入队后命令可能已在执行中的事务里,必须等到结果,不能以单条 Apply 另行结算。 + out := <-req.done + return out.Result, out.Err +} + +func (c *UsageBillingLaneCombiner) ReserveBatchImageBalance(ctx context.Context, cmd *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) { + return c.repo.ReserveBatchImageBalance(ctx, cmd) +} + +func (c *UsageBillingLaneCombiner) CaptureBatchImageBalance(ctx context.Context, cmd *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) { + return c.repo.CaptureBatchImageBalance(ctx, cmd) +} + +func (c *UsageBillingLaneCombiner) ReleaseBatchImageBalance(ctx context.Context, cmd *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) { + return c.repo.ReleaseBatchImageBalance(ctx, cmd) +} + +// Stop 拒收新命令(之后的 Apply 直接调用底层仓储),并等待所有通道结算完已排队的命令。可重复调用。 +func (c *UsageBillingLaneCombiner) Stop() { + if c == nil { + return + } + for i := range c.shards { + shard := &c.shards[i] + shard.mu.Lock() + shard.closed = true + shard.mu.Unlock() + } + c.wg.Wait() + stats := c.Stats() + logger.LegacyPrintf("service.usage_billing_lane", "[UsageBillingLane] stopped: single=%d batches=%d batched_commands=%d fallbacks=%d max_batch=%d", + stats.SingleApplies, stats.Batches, stats.BatchedCommands, stats.BatchFallbacks, stats.MaxBatchSize) +} + +// Stats 返回累计计数。 +func (c *UsageBillingLaneCombiner) Stats() UsageBillingLaneStats { + return UsageBillingLaneStats{ + SingleApplies: c.singleApplies.Load(), + Batches: c.batches.Load(), + BatchedCommands: c.batchedCommands.Load(), + BatchFallbacks: c.batchFallbacks.Load(), + MaxBatchSize: c.maxBatchSeen.Load(), + } +} + +func (c *UsageBillingLaneCombiner) shardFor(userID int64) *usageBillingLaneShard { + return &c.shards[uint64(userID)%usageBillingLaneShardCount] +} + +// enqueue 把命令追加到用户通道;通道不存在时创建并启动结算 goroutine。已停止时返回 false。 +func (c *UsageBillingLaneCombiner) enqueue(req *usageBillingLaneRequest) bool { + userID := req.cmd.UserID + shard := c.shardFor(userID) + shard.mu.Lock() + defer shard.mu.Unlock() + if shard.closed { + return false + } + if lane, ok := shard.lanes[userID]; ok { + lane.pending = append(lane.pending, req) + return true + } + lane := &usageBillingLane{pending: []*usageBillingLaneRequest{req}} + shard.lanes[userID] = lane + c.wg.Add(1) + go c.drain(shard, userID, lane) + return true +} + +// drain 循环取出通道中排队的命令结算,队列为空时在同一把锁内移除通道并退出。 +func (c *UsageBillingLaneCombiner) drain(shard *usageBillingLaneShard, userID int64, lane *usageBillingLane) { + defer c.wg.Done() + for { + batch := c.take(shard, userID, lane) + if len(batch) == 0 { + return + } + c.execute(batch) + } +} + +func (c *UsageBillingLaneCombiner) take(shard *usageBillingLaneShard, userID int64, lane *usageBillingLane) []*usageBillingLaneRequest { + shard.mu.Lock() + defer shard.mu.Unlock() + n := len(lane.pending) + if n == 0 { + delete(shard.lanes, userID) + return nil + } + if n <= c.maxBatch { + batch := lane.pending + lane.pending = nil + return batch + } + batch := lane.pending[:c.maxBatch:c.maxBatch] + lane.pending = append([]*usageBillingLaneRequest(nil), lane.pending[c.maxBatch:]...) + return batch +} + +// execute 结算一批命令并把结果交给各自的调用方;任何路径(含 panic)下每个请求都恰好收到一次结果。 +func (c *UsageBillingLaneCombiner) execute(batch []*usageBillingLaneRequest) { + defer func() { + if r := recover(); r != nil { + logger.LegacyPrintf("service.usage_billing_lane", "[UsageBillingLane] ALERT: panic while settling user=%d batch=%d: %v", + batch[0].cmd.UserID, len(batch), r) + err := fmt.Errorf("usage billing lane panic: %v", r) + for _, req := range batch { + deliverUsageBillingLaneResult(req, nil, err) + } + } + }() + + if len(batch) == 1 { + c.singleApplies.Add(1) + c.applyOne(batch[0], time.Now().Add(postUsageBillingTimeout)) + return + } + + c.recordBatch(len(batch)) + cmds := make([]*UsageBillingCommand, len(batch)) + for i, req := range batch { + cmds[i] = req.cmd + } + outcomes, err := c.applyBatch(batch[0].ctx, cmds) + if err == nil && len(outcomes) != len(batch) { + err = errUsageBillingLaneBatchOutcomeMismatch + } + if err == nil { + for i, req := range batch { + deliverUsageBillingLaneResult(req, outcomes[i].Result, outcomes[i].Err) + } + return + } + + c.logBatchFallback(batch[0].cmd.UserID, len(batch), err) + // 整批逐条结算共用一个截止时间,数据库不可用时整批在一个超时内结束。 + deadline := time.Now().Add(postUsageBillingTimeout) + for _, req := range batch { + c.applyOne(req, deadline) + } +} + +// applyOne 以单条 Apply 结算一个请求并交付结果。上下文保留请求上下文中的值,截止时间为 deadline; +// panic 视同该请求返回 error。 +func (c *UsageBillingLaneCombiner) applyOne(req *usageBillingLaneRequest, deadline time.Time) { + ctx, cancel := context.WithDeadline(context.WithoutCancel(req.ctx), deadline) + defer cancel() + res, err := func() (res *UsageBillingApplyResult, err error) { + defer func() { + if r := recover(); r != nil { + logger.LegacyPrintf("service.usage_billing_lane", "[UsageBillingLane] ALERT: panic while applying user=%d request=%s: %v", + req.cmd.UserID, req.cmd.RequestID, r) + res, err = nil, fmt.Errorf("usage billing apply panic: %v", r) + } + }() + return c.repo.Apply(ctx, req.cmd) + }() + deliverUsageBillingLaneResult(req, res, err) +} + +// applyBatch 调用底层 ApplyBatch,panic 视同返回 error(事务已由底层回滚)。 +func (c *UsageBillingLaneCombiner) applyBatch(ctx context.Context, cmds []*UsageBillingCommand) (outcomes []UsageBillingBatchOutcome, err error) { + batchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), postUsageBillingTimeout) + defer cancel() + defer func() { + if r := recover(); r != nil { + logger.LegacyPrintf("service.usage_billing_lane", "[UsageBillingLane] ALERT: panic while settling user=%d batch=%d: %v", + cmds[0].UserID, len(cmds), r) + outcomes, err = nil, fmt.Errorf("usage billing batch panic: %v", r) + } + }() + return c.repo.ApplyBatch(batchCtx, cmds) +} + +// logBatchFallback 计数并记录一次整批回退;日志每分钟至多一条,带累计回退次数。 +func (c *UsageBillingLaneCombiner) logBatchFallback(userID int64, size int, err error) { + total := c.batchFallbacks.Add(1) + now := time.Now().UnixNano() + last := c.lastFallbackLog.Load() + if now-last < int64(usageBillingLaneFallbackLogInterval) || !c.lastFallbackLog.CompareAndSwap(last, now) { + return + } + logger.LegacyPrintf("service.usage_billing_lane", "[UsageBillingLane] batch settle failed, applying one by one: user=%d batch=%d total_fallbacks=%d err=%v", + userID, size, total, err) +} + +func (c *UsageBillingLaneCombiner) recordBatch(size int) { + c.batches.Add(1) + c.batchedCommands.Add(uint64(size)) + for { + prev := c.maxBatchSeen.Load() + if uint64(size) <= prev || c.maxBatchSeen.CompareAndSwap(prev, uint64(size)) { + return + } + } +} + +// deliverUsageBillingLaneResult 把结果交给请求方;已交付过的请求忽略。只在通道的结算 goroutine 中调用。 +func deliverUsageBillingLaneResult(req *usageBillingLaneRequest, res *UsageBillingApplyResult, err error) { + if req.delivered { + return + } + req.delivered = true + if err != nil { + res = nil + } + req.done <- UsageBillingBatchOutcome{Result: res, Err: err} +} diff --git a/backend/internal/service/usage_billing_lane_test.go b/backend/internal/service/usage_billing_lane_test.go new file mode 100644 index 0000000000..928e20f2a5 --- /dev/null +++ b/backend/internal/service/usage_billing_lane_test.go @@ -0,0 +1,616 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "math/rand" + "sort" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// laneTestRepo 按用户记账:Apply 与 ApplyBatch 都按命令顺序扣减余额并返回扣后余额, +// 同时记录每个用户的并发执行数。 +type laneTestRepo struct { + mu sync.Mutex + balances map[int64]float64 + applyCalls []string + batchCalls [][]string + inflight map[int64]int + maxInflight int + + // gate 非 nil 时,requestID 在其中的命令在结算前阻塞到对应 channel 关闭。 + gate map[string]chan struct{} + // started 每条命令开始结算时写入其 requestID。 + started chan string + + batchErr error + batchPanic bool + applyPanic map[string]bool + outcomeErrs map[string]error + holdCalls atomic.Int32 + // deadlines 记录每条单条 Apply 收到的上下文截止时间。 + deadlines map[string]time.Time +} + +func newLaneTestRepo() *laneTestRepo { + return &laneTestRepo{ + balances: map[int64]float64{}, + inflight: map[int64]int{}, + gate: map[string]chan struct{}{}, + started: make(chan string, 4096), + applyPanic: map[string]bool{}, + outcomeErrs: map[string]error{}, + deadlines: map[string]time.Time{}, + } +} + +func (r *laneTestRepo) enter(userID int64) { + r.mu.Lock() + defer r.mu.Unlock() + r.inflight[userID]++ + if r.inflight[userID] > r.maxInflight { + r.maxInflight = r.inflight[userID] + } +} + +func (r *laneTestRepo) leave(userID int64) { + r.mu.Lock() + defer r.mu.Unlock() + r.inflight[userID]-- +} + +func (r *laneTestRepo) wait(requestID string) { + r.mu.Lock() + ch := r.gate[requestID] + r.mu.Unlock() + if ch != nil { + <-ch + } +} + +func (r *laneTestRepo) deduct(cmd *UsageBillingCommand) *UsageBillingApplyResult { + r.mu.Lock() + defer r.mu.Unlock() + r.balances[cmd.UserID] -= cmd.BalanceCost + balance := r.balances[cmd.UserID] + return &UsageBillingApplyResult{Applied: true, NewBalance: &balance} +} + +func (r *laneTestRepo) Apply(ctx context.Context, cmd *UsageBillingCommand) (*UsageBillingApplyResult, error) { + r.enter(cmd.UserID) + defer r.leave(cmd.UserID) + r.started <- cmd.RequestID + r.wait(cmd.RequestID) + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.Lock() + r.applyCalls = append(r.applyCalls, cmd.RequestID) + if deadline, ok := ctx.Deadline(); ok { + r.deadlines[cmd.RequestID] = deadline + } + panicNow := r.applyPanic[cmd.RequestID] + outcomeErr := r.outcomeErrs[cmd.RequestID] + r.mu.Unlock() + if panicNow { + panic("apply boom") + } + if outcomeErr != nil { + return nil, outcomeErr + } + return r.deduct(cmd), nil +} + +func (r *laneTestRepo) ApplyBatch(_ context.Context, cmds []*UsageBillingCommand) ([]UsageBillingBatchOutcome, error) { + userID := cmds[0].UserID + r.enter(userID) + defer r.leave(userID) + ids := make([]string, len(cmds)) + for i, cmd := range cmds { + ids[i] = cmd.RequestID + r.started <- cmd.RequestID + } + for _, cmd := range cmds { + r.wait(cmd.RequestID) + } + r.mu.Lock() + r.batchCalls = append(r.batchCalls, ids) + batchErr, batchPanic := r.batchErr, r.batchPanic + r.mu.Unlock() + if batchPanic { + panic("batch boom") + } + if batchErr != nil { + return nil, batchErr + } + out := make([]UsageBillingBatchOutcome, len(cmds)) + for i, cmd := range cmds { + r.mu.Lock() + err := r.outcomeErrs[cmd.RequestID] + r.mu.Unlock() + if err != nil { + out[i] = UsageBillingBatchOutcome{Err: err} + continue + } + out[i] = UsageBillingBatchOutcome{Result: r.deduct(cmd)} + } + return out, nil +} + +func (r *laneTestRepo) ReserveBatchImageBalance(context.Context, *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) { + r.holdCalls.Add(1) + return &BatchImageBalanceHoldResult{Applied: true}, nil +} + +func (r *laneTestRepo) CaptureBatchImageBalance(context.Context, *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) { + r.holdCalls.Add(1) + return &BatchImageBalanceHoldResult{Applied: true}, nil +} + +func (r *laneTestRepo) ReleaseBatchImageBalance(context.Context, *BatchImageBalanceHoldCommand) (*BatchImageBalanceHoldResult, error) { + r.holdCalls.Add(1) + return &BatchImageBalanceHoldResult{Applied: true}, nil +} + +func (r *laneTestRepo) block(requestID string) chan struct{} { + ch := make(chan struct{}) + r.mu.Lock() + r.gate[requestID] = ch + r.mu.Unlock() + return ch +} + +func newLaneTestCombiner(repo UsageBillingBatchRepository, maxBatch int) *UsageBillingLaneCombiner { + return newUsageBillingLaneCombiner(repo, maxBatch) +} + +func laneTestCommand(userID int64, requestID string, cost float64) *UsageBillingCommand { + return &UsageBillingCommand{RequestID: requestID, APIKeyID: 1, UserID: userID, BalanceCost: cost} +} + +type laneTestResult struct { + requestID string + res *UsageBillingApplyResult + err error +} + +func applyAsync(c *UsageBillingLaneCombiner, cmd *UsageBillingCommand, out chan<- laneTestResult) { + go func() { + res, err := c.Apply(context.Background(), cmd) + out <- laneTestResult{requestID: cmd.RequestID, res: res, err: err} + }() +} + +func waitStarted(t *testing.T, repo *laneTestRepo, requestID string) { + t.Helper() + select { + case got := <-repo.started: + require.Equal(t, requestID, got) + case <-time.After(5 * time.Second): + t.Fatalf("request %s did not start", requestID) + } +} + +func waitPending(t *testing.T, c *UsageBillingLaneCombiner, userID int64, n int) { + t.Helper() + require.Eventually(t, func() bool { + shard := c.shardFor(userID) + shard.mu.Lock() + defer shard.mu.Unlock() + lane := shard.lanes[userID] + return lane != nil && len(lane.pending) == n + }, 5*time.Second, time.Millisecond) +} + +func laneCount(c *UsageBillingLaneCombiner) int { + total := 0 + for i := range c.shards { + shard := &c.shards[i] + shard.mu.Lock() + total += len(shard.lanes) + shard.mu.Unlock() + } + return total +} + +func collectResults(t *testing.T, out <-chan laneTestResult, n int) map[string]laneTestResult { + t.Helper() + results := make(map[string]laneTestResult, n) + for i := 0; i < n; i++ { + select { + case r := <-out: + results[r.requestID] = r + case <-time.After(10 * time.Second): + t.Fatalf("only %d/%d results received", i, n) + } + } + return results +} + +func TestUsageBillingLane_HoldMethodsPassThrough(t *testing.T) { + repo := newLaneTestRepo() + c := newLaneTestCombiner(repo, 8) + ctx := context.Background() + + _, err := c.ReserveBatchImageBalance(ctx, &BatchImageBalanceHoldCommand{}) + require.NoError(t, err) + _, err = c.CaptureBatchImageBalance(ctx, &BatchImageBalanceHoldCommand{}) + require.NoError(t, err) + _, err = c.ReleaseBatchImageBalance(ctx, &BatchImageBalanceHoldCommand{}) + require.NoError(t, err) + require.EqualValues(t, 3, repo.holdCalls.Load()) +} + +func TestUsageBillingLane_MissingRequestIDAppliesDirectly(t *testing.T) { + repo := newLaneTestRepo() + c := newLaneTestCombiner(repo, 8) + + res, err := c.Apply(context.Background(), laneTestCommand(7, " ", 1)) + require.NoError(t, err) + require.True(t, res.Applied) + require.Zero(t, c.Stats().SingleApplies) + require.Zero(t, laneCount(c)) +} + +func TestUsageBillingLane_IdleLaneAppliesImmediately(t *testing.T) { + repo := newLaneTestRepo() + repo.balances[7] = 10 + c := newLaneTestCombiner(repo, 8) + + res, err := c.Apply(context.Background(), laneTestCommand(7, "r1", 1.5)) + require.NoError(t, err) + require.True(t, res.Applied) + require.Equal(t, 8.5, *res.NewBalance) + require.Equal(t, []string{"r1"}, repo.applyCalls) + require.Empty(t, repo.batchCalls) + require.EqualValues(t, 1, c.Stats().SingleApplies) + require.Eventually(t, func() bool { return laneCount(c) == 0 }, time.Second, time.Millisecond) +} + +func TestUsageBillingLane_QueuedRequestsSettleAsOneBatch(t *testing.T) { + repo := newLaneTestRepo() + repo.balances[7] = 100 + c := newLaneTestCombiner(repo, 64) + out := make(chan laneTestResult, 16) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + + for i := 0; i < 5; i++ { + applyAsync(c, laneTestCommand(7, fmt.Sprintf("q%d", i), float64(i+1)), out) + } + waitPending(t, c, 7, 5) + close(release) + + results := collectResults(t, out, 6) + for id, r := range results { + require.NoError(t, r.err, id) + require.True(t, r.res.Applied, id) + } + + require.Equal(t, []string{"first"}, repo.applyCalls) + require.Len(t, repo.batchCalls, 1) + require.ElementsMatch(t, []string{"q0", "q1", "q2", "q3", "q4"}, repo.batchCalls[0]) + + // 每个调用方拿到的是自己那条命令在批内顺序下的扣后余额。 + running := 99.0 + for _, id := range repo.batchCalls[0] { + var cost float64 + _, _ = fmt.Sscanf(id, "q%f", &cost) + running -= cost + 1 + require.Equal(t, running, *results[id].res.NewBalance, id) + } + require.Equal(t, 84.0, repo.balances[7]) + + stats := c.Stats() + require.EqualValues(t, 1, stats.SingleApplies) + require.EqualValues(t, 1, stats.Batches) + require.EqualValues(t, 5, stats.BatchedCommands) + require.EqualValues(t, 5, stats.MaxBatchSize) + require.Equal(t, 1, repo.maxInflight) + require.Eventually(t, func() bool { return laneCount(c) == 0 }, time.Second, time.Millisecond) +} + +func TestUsageBillingLane_DifferentUsersSettleIndependently(t *testing.T) { + repo := newLaneTestRepo() + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 4) + + release := repo.block("a1") + applyAsync(c, laneTestCommand(1, "a1", 1), out) + waitStarted(t, repo, "a1") + + res, err := c.Apply(context.Background(), laneTestCommand(2, "b1", 1)) + require.NoError(t, err) + require.True(t, res.Applied) + + close(release) + collectResults(t, out, 1) +} + +func TestUsageBillingLane_SplitsQueueByMaxBatchSize(t *testing.T) { + repo := newLaneTestRepo() + c := newLaneTestCombiner(repo, 3) + out := make(chan laneTestResult, 16) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + for i := 0; i < 7; i++ { + applyAsync(c, laneTestCommand(7, fmt.Sprintf("q%d", i), 1), out) + waitPending(t, c, 7, i+1) + } + close(release) + + results := collectResults(t, out, 8) + for id, r := range results { + require.NoError(t, r.err, id) + } + require.Len(t, repo.batchCalls, 2) + require.Equal(t, []string{"q0", "q1", "q2"}, repo.batchCalls[0]) + require.Equal(t, []string{"q3", "q4", "q5"}, repo.batchCalls[1]) + require.Equal(t, []string{"first", "q6"}, repo.applyCalls) + require.EqualValues(t, 3, c.Stats().MaxBatchSize) +} + +func TestUsageBillingLane_BatchErrorFallsBackToSingleApply(t *testing.T) { + for _, tc := range []struct { + name string + setup func(*laneTestRepo) + }{ + {name: "error", setup: func(r *laneTestRepo) { r.batchErr = errors.New("batch failed") }}, + {name: "panic", setup: func(r *laneTestRepo) { r.batchPanic = true }}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := newLaneTestRepo() + repo.balances[7] = 10 + tc.setup(repo) + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 8) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + applyAsync(c, laneTestCommand(7, "q0", 2), out) + waitPending(t, c, 7, 1) + applyAsync(c, laneTestCommand(7, "q1", 3), out) + waitPending(t, c, 7, 2) + close(release) + + results := collectResults(t, out, 3) + for id, r := range results { + require.NoError(t, r.err, id) + require.True(t, r.res.Applied, id) + } + require.Equal(t, []string{"first", "q0", "q1"}, repo.applyCalls) + require.Equal(t, 7.0, *results["q0"].res.NewBalance) + require.Equal(t, 4.0, *results["q1"].res.NewBalance) + require.EqualValues(t, 1, c.Stats().BatchFallbacks) + }) + } +} + +func TestUsageBillingLane_PerCommandOutcomeErrorReachesItsCaller(t *testing.T) { + repo := newLaneTestRepo() + repo.outcomeErrs["q1"] = ErrUsageBillingRequestConflict + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 8) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + applyAsync(c, laneTestCommand(7, "q0", 1), out) + applyAsync(c, laneTestCommand(7, "q1", 1), out) + waitPending(t, c, 7, 2) + close(release) + + results := collectResults(t, out, 3) + require.NoError(t, results["q0"].err) + require.ErrorIs(t, results["q1"].err, ErrUsageBillingRequestConflict) + require.Nil(t, results["q1"].res) + require.Zero(t, c.Stats().BatchFallbacks) +} + +func TestUsageBillingLane_ApplyPanicDeliversErrorAndLaneKeepsWorking(t *testing.T) { + repo := newLaneTestRepo() + repo.applyPanic["boom"] = true + c := newLaneTestCombiner(repo, 8) + + res, err := c.Apply(context.Background(), laneTestCommand(7, "boom", 1)) + require.Error(t, err) + require.Nil(t, res) + + res, err = c.Apply(context.Background(), laneTestCommand(7, "after", 1)) + require.NoError(t, err) + require.True(t, res.Applied) + require.Eventually(t, func() bool { return laneCount(c) == 0 }, time.Second, time.Millisecond) +} + +func TestUsageBillingLane_StopWaitsForQueuedCommandsThenBypassesLanes(t *testing.T) { + repo := newLaneTestRepo() + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 8) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + applyAsync(c, laneTestCommand(7, "q0", 1), out) + waitPending(t, c, 7, 1) + + stopped := make(chan struct{}) + go func() { + c.Stop() + close(stopped) + }() + select { + case <-stopped: + t.Fatal("Stop returned while a lane still had queued commands") + case <-time.After(50 * time.Millisecond): + } + + close(release) + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Fatal("Stop did not return after lanes drained") + } + results := collectResults(t, out, 2) + require.NoError(t, results["first"].err) + require.NoError(t, results["q0"].err) + + before := c.Stats() + res, err := c.Apply(context.Background(), laneTestCommand(7, "late", 1)) + require.NoError(t, err) + require.True(t, res.Applied) + require.Equal(t, before, c.Stats()) + require.Zero(t, laneCount(c)) + + c.Stop() +} + +func TestUsageBillingLane_StopOnNilCombiner(t *testing.T) { + var c *UsageBillingLaneCombiner + require.NotPanics(t, c.Stop) +} + +func TestUsageBillingLane_ConcurrentUsersReceiveTheirOwnResults(t *testing.T) { + const ( + users = 24 + perUser = 60 + initBalance = 1_000_000.0 + ) + repo := newLaneTestRepo() + for u := int64(1); u <= users; u++ { + repo.balances[u] = initBalance + } + c := newLaneTestCombiner(repo, 16) + + type call struct { + userID int64 + cost float64 + res *UsageBillingApplyResult + err error + } + calls := make([]*call, 0, users*perUser) + for u := int64(1); u <= users; u++ { + for i := 0; i < perUser; i++ { + calls = append(calls, &call{userID: u, cost: float64(rand.Intn(1000) + 1)}) + } + } + + var wg sync.WaitGroup + for i, cl := range calls { + wg.Add(1) + go func(i int, cl *call) { + defer wg.Done() + if i%7 == 0 { + time.Sleep(time.Duration(rand.Intn(200)) * time.Microsecond) + } + cl.res, cl.err = c.Apply(context.Background(), laneTestCommand(cl.userID, fmt.Sprintf("u%d-%d", cl.userID, i), cl.cost)) + }(i, cl) + } + wg.Wait() + + byUser := map[int64][]*call{} + for _, cl := range calls { + require.NoError(t, cl.err) + require.True(t, cl.res.Applied) + byUser[cl.userID] = append(byUser[cl.userID], cl) + } + for u, list := range byUser { + // 按扣后余额从高到低排列时,相邻两条的差恰好是后一条的费用:每条结果对应同一用户串行扣费序列中的一个位置。 + sort.Slice(list, func(a, b int) bool { return *list[a].res.NewBalance > *list[b].res.NewBalance }) + prev := initBalance + total := 0.0 + for _, cl := range list { + require.Equal(t, prev-cl.cost, *cl.res.NewBalance, "user %d", u) + prev = *cl.res.NewBalance + total += cl.cost + } + require.Equal(t, initBalance-total, repo.balances[u]) + } + require.Equal(t, 1, repo.maxInflight, "a user must never have two settlements running at once") + require.Eventually(t, func() bool { return laneCount(c) == 0 }, time.Second, time.Millisecond) + c.Stop() +} + +func TestUsageBillingLane_QueuedRequestTimeoutStartsWhenSettlementStarts(t *testing.T) { + repo := newLaneTestRepo() + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 4) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + + // 调用方的截止时间在排队期间到期;单独结算时仍以开始结算的时刻计算超时。 + callerCtx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + go func() { + res, err := c.Apply(callerCtx, laneTestCommand(7, "queued", 1)) + out <- laneTestResult{requestID: "queued", res: res, err: err} + }() + waitPending(t, c, 7, 1) + <-callerCtx.Done() + close(release) + + results := collectResults(t, out, 2) + require.NoError(t, results["queued"].err) + require.True(t, results["queued"].res.Applied) + require.Greater(t, time.Until(repo.deadlines["queued"]), postUsageBillingTimeout-5*time.Second) +} + +func TestUsageBillingLane_FallbackSharesOneDeadline(t *testing.T) { + repo := newLaneTestRepo() + repo.batchErr = errors.New("batch failed") + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 8) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + for i := 0; i < 3; i++ { + applyAsync(c, laneTestCommand(7, fmt.Sprintf("q%d", i), 1), out) + waitPending(t, c, 7, i+1) + } + close(release) + + results := collectResults(t, out, 4) + for id, r := range results { + require.NoError(t, r.err, id) + } + require.Equal(t, repo.deadlines["q0"], repo.deadlines["q1"]) + require.Equal(t, repo.deadlines["q0"], repo.deadlines["q2"]) +} + +func TestUsageBillingLane_FallbackPanicOnlyFailsThatRequest(t *testing.T) { + repo := newLaneTestRepo() + repo.batchErr = errors.New("batch failed") + repo.applyPanic["q0"] = true + c := newLaneTestCombiner(repo, 8) + out := make(chan laneTestResult, 8) + + release := repo.block("first") + applyAsync(c, laneTestCommand(7, "first", 1), out) + waitStarted(t, repo, "first") + applyAsync(c, laneTestCommand(7, "q0", 1), out) + waitPending(t, c, 7, 1) + applyAsync(c, laneTestCommand(7, "q1", 1), out) + waitPending(t, c, 7, 2) + close(release) + + results := collectResults(t, out, 3) + require.Error(t, results["q0"].err) + require.Nil(t, results["q0"].res) + require.NoError(t, results["q1"].err) + require.True(t, results["q1"].res.Applied) +} diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index d24d33a1a4..efa0c2587e 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -993,8 +993,15 @@ var ProviderSet = wire.NewSet( ProvideChannelMonitorV2Aggregator, NewChannelMonitorRequestTemplateService, ProvideUserPlatformQuotaUsageFlusher, + NewUsageBillingLaneCombiner, + ProvideUsageBillingRepository, ) +// ProvideUsageBillingRepository 以按用户合并结算的通道作为各服务使用的计费仓储。 +func ProvideUsageBillingRepository(lanes *UsageBillingLaneCombiner) UsageBillingRepository { + return lanes +} + // ProvideUserPlatformQuotaUsageFlusher 创建并启动 UserPlatformQuotaUsageFlusher。 func ProvideUserPlatformQuotaUsageFlusher(cfg *config.Config, cache BillingCache, quotaRepo UserPlatformQuotaRepository, tw *TimingWheelService) *UserPlatformQuotaUsageFlusher { svc := NewUserPlatformQuotaUsageFlusher(cfg, cache, quotaRepo, tw) From ade20f4e4749b743dab268e006d3ad10b58af554 Mon Sep 17 00:00:00 2001 From: feeeei Date: Sat, 14 Nov 2026 11:40:42 +0800 Subject: [PATCH 68/85] =?UTF-8?q?perf(gateway):=20=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E4=BD=93=E7=83=AD=E7=82=B9=E8=B7=AF=E5=BE=84=E6=94=B9=E7=94=A8?= =?UTF-8?q?=E9=9B=B6=E6=8B=B7=E8=B4=9D=E8=AF=BB=E5=8F=96=EF=BC=8C=E5=87=8F?= =?UTF-8?q?=E5=B0=91=E6=95=B4=E6=AE=B5=E8=A7=A3=E7=A0=81=E4=B8=8E=E5=A4=8D?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 大请求体上,几个只读检查一遇到任意 \u 转义就整段解码,gjson.GetBytes 会复制整段 input/messages,sjson 删除不存在的键时也会先复制整个 body。 - 新增 JSONMayEscapePlainASCII:成对扫描 JSON 转义,只有能拼出可见 ASCII 的 \u 才让 字面量快速判断失效;控制字符、HTML 安全转义和非 ASCII 字符的转义不再触发完整解码。 用于 codex bootstrap / page context 候选、compaction_trigger、input_image、 additional_tools 的快速判断。 - OpenAI Responses: - namespace 声明、tools 判断、空 base64 图片、compaction_trigger 检测与 namespace 剥离改用 parseRawJSONView,不再复制整段 input/tools。 - compaction_trigger 只字面出现一次且是 input 最后一项的 type 时跳过完整解码。 - codex 调用输出候选在字面量命中后,用零拷贝视图确认 input 中确有对应名字的 function_call_output 项;只在工具声明里出现同名时不再做唯一性扫描和完整解码。 - Bedrock: - 顶层字段删除前先用零拷贝视图确认存在。 - cache_control 清理和流事件 bytes 字段改用零拷贝读取。 - NormalizeMaxReasoningEffort 复用包级 strings.Replacer。 合法 JSON 上行为不变,新增测试与总走解码/复制的参考实现做差分比较。只在非法或病态 body 上有差异:嵌套超过 10000 层且只含非 ASCII 转义、或 trigger 已在末尾时,不再报 解码深度错误(gjson 校验没有深度上限,无字面量 body 原本即如此);开头带非 JSON 前缀的非法 body,零拷贝视图读不到其后的对象,这类 body 随后仍被 JSON 校验拒绝。 --- .../openai_codex_call_output_gate_test.go | 63 ++++ .../handler/openai_gateway_handler.go | 18 +- backend/internal/service/bedrock_request.go | 81 +++-- backend/internal/service/bedrock_stream.go | 3 +- .../service/hot_path_zero_copy_test.go | 312 ++++++++++++++++++ backend/internal/service/json_escape_probe.go | 71 ++++ .../service/json_escape_probe_test.go | 38 +++ .../service/openai_call_output_probe.go | 35 ++ .../service/openai_compact_body_signal.go | 53 ++- .../service/openai_gateway_request_body.go | 49 ++- .../service/openai_reasoning_effort_policy.go | 4 +- .../service/openai_responses_namespace.go | 9 +- 12 files changed, 671 insertions(+), 65 deletions(-) create mode 100644 backend/internal/handler/openai_codex_call_output_gate_test.go create mode 100644 backend/internal/service/hot_path_zero_copy_test.go create mode 100644 backend/internal/service/json_escape_probe.go create mode 100644 backend/internal/service/json_escape_probe_test.go create mode 100644 backend/internal/service/openai_call_output_probe.go diff --git a/backend/internal/handler/openai_codex_call_output_gate_test.go b/backend/internal/handler/openai_codex_call_output_gate_test.go new file mode 100644 index 0000000000..3dbff2d493 --- /dev/null +++ b/backend/internal/handler/openai_codex_call_output_gate_test.go @@ -0,0 +1,63 @@ +//go:build unit + +package handler + +import ( + "math/rand" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCodexCallOutputGateSkipsDeclaredToolsWithoutCandidate(t *testing.T) { + body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"},{"type":"function","name":"create_thread"}],` + + `"input":[{"type":"function_call","call_id":"c1","name":"shell"},{"type":"function_call_output","call_id":"c1","output":"ok"}]}`) + require.False(t, mayContainCodexCallOutputCandidate(body, "automation_update")) + require.False(t, mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread")) + for name, normalize := range map[string]func([]byte) ([]byte, bool){ + "page": normalizeCodexPageContext, + "automation": normalizeCodexAutomationBootstrap, + "delegation": normalizeCodexDelegationBootstrap, + } { + t.Run(name, func(t *testing.T) { + allocs := testing.AllocsPerRun(10, func() { + got, changed := normalize(body) + if changed || &got[0] != &body[0] { + t.Fatal("non-candidate body must be returned unchanged") + } + }) + require.Zero(t, allocs) + }) + } +} + +// Whenever the ungated bootstrap path rewrites a body, the gate must admit it. +func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) { + u := func(hex string) string { return `\` + "u" + hex } + output := mustJSON(t, codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt)) + items := []string{ + `{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`, + `{"type":"function_call_output","namespace":"codex_app","name":"` + u("0061") + `utomation_update","output":` + output + `}`, + `{"` + u("0074") + `ype":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`, + `{"type":"function_call_output","namespace":"codex_app","name":"automation_update","name":"other","output":` + output + `}`, + `{"type":"function_call_output","call_id":"c","output":"ok"}`, + `{"type":"message","role":"user","content":"automation_update function_call_output caf` + u("00e9") + `"}`, + `{"type":"function_call","call_id":"c","name":"automation_update"}`, + } + rng := rand.New(rand.NewSource(11)) + rewrites := 0 + for i := 0; i < 3000; i++ { + var parts []string + for n := rng.Intn(3); n >= 0; n-- { + parts = append(parts, items[rng.Intn(len(items))]) + } + body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"}],"input":[` + strings.Join(parts, ",") + `]}`) + _, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false) + if rewritten { + rewrites++ + require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body) + } + } + require.Positive(t, rewrites) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index f70bce78b2..8822672422 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1729,11 +1729,23 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) { // mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap // candidate, checked before the full uniqueness scan and decode. Its type and // tool name are JSON strings, which appear literally unless a \u escape spells -// their letters; without either, normalization cannot change the body. +// their letters; without either, normalization cannot change the body. Escapes +// that real clients emit (control characters, HTML-safe and non-ASCII runes) +// cannot spell those letters and must not force the full decode. +// +// Tool declarations carry the same names, so a literal hit is confirmed by a +// zero-copy scan for an input item of type function_call_output whose name +// starts with one of toolNames. The full path rejects bodies with duplicate +// members, and without duplicates the scan reads the same values as the +// decoder. func mayContainCodexCallOutputCandidate(body []byte, toolNames ...string) bool { - if bytes.Contains(body, []byte(`\u`)) { - return true + if !service.JSONMayEscapePlainASCII(body) && !containsCodexCallOutputLiterals(body, toolNames) { + return false } + return service.ResponsesInputHasFunctionCallOutputNamed(body, toolNames...) +} + +func containsCodexCallOutputLiterals(body []byte, toolNames []string) bool { if !bytes.Contains(body, []byte("function_call_output")) { return false } diff --git a/backend/internal/service/bedrock_request.go b/backend/internal/service/bedrock_request.go index 4fc7fd7213..74df923e63 100644 --- a/backend/internal/service/bedrock_request.go +++ b/backend/internal/service/bedrock_request.go @@ -226,21 +226,21 @@ func PrepareBedrockRequestBodyWithTokens(body []byte, modelID string, betaTokens } logger.LegacyPrintf("service.gateway", "[Bedrock] Injected beta tokens: %v (model=%s ccCompat=%v)", betaTokens, modelID, ccCompat) } else { - body, _ = sjson.DeleteBytes(body, "anthropic_beta") + body, _ = deleteJSONPathIfPresent(body, "anthropic_beta") } // 移除 Bedrock 不支持的 Anthropic 直连 API 专有顶层字段 - body, _ = sjson.DeleteBytes(body, "provider") - body, _ = sjson.DeleteBytes(body, "metadata") + body, _ = deleteJSONPathIfPresent(body, "provider") + body, _ = deleteJSONPathIfPresent(body, "metadata") // 移除 model 字段(Bedrock 通过 URL 指定模型) - body, err = sjson.DeleteBytes(body, "model") + body, err = deleteJSONPathIfPresent(body, "model") if err != nil { return nil, fmt.Errorf("remove model field: %w", err) } // 移除 stream 字段(Bedrock 通过不同端点控制流式,不接受请求体中的 stream 字段) - body, err = sjson.DeleteBytes(body, "stream") + body, err = deleteJSONPathIfPresent(body, "stream") if err != nil { return nil, fmt.Errorf("remove stream field: %w", err) } @@ -256,10 +256,10 @@ func PrepareBedrockRequestBodyWithTokens(body []byte, modelID string, betaTokens if effort := gjson.GetBytes(body, "output_config.effort"); effort.Exists() { body, err = sjson.SetRawBytes(body, "output_config", []byte(`{"effort":`+effort.Raw+`}`)) } else { - body, err = sjson.DeleteBytes(body, "output_config") + body, err = deleteJSONPathIfPresent(body, "output_config") } } else { - body, err = sjson.DeleteBytes(body, "output_config") + body, err = deleteJSONPathIfPresent(body, "output_config") } if err != nil { return nil, fmt.Errorf("normalize output_config field: %w", err) @@ -289,6 +289,16 @@ func ResolveBedrockBetaTokens(betaHeader string, body []byte, modelID string) [] return filterBedrockBetaTokens(betaTokens) } +// deleteJSONPathIfPresent 删除 path 指向的值。sjson 在值不存在时也会先复制整个 +// body 再丢弃,所以先用零拷贝视图确认存在;不存在时原样返回 body。path 只能是 +// gjson 与 sjson 语义一致的简单路径。 +func deleteJSONPathIfPresent(body []byte, path string) ([]byte, error) { + if !parseRawJSONView(body).Get(path).Exists() { + return body, nil + } + return sjson.DeleteBytes(body, path) +} + // convertOutputFormatToInlineSchema 将结构化输出的 JSON schema 内联到最后一条 user message // Bedrock Invoke 不支持 output_format 参数,litellm 的做法是将 schema 追加到用户消息中 // 参考: litellm AmazonAnthropicClaudeMessagesConfig._convert_output_format_to_inline_schema() @@ -402,45 +412,44 @@ func isBedrockClaude45OrNewer(modelID string) bool { func sanitizeBedrockCacheControl(body []byte, modelID string) []byte { isClaude45 := isBedrockClaude45OrNewer(modelID) + // 两段扫描都读零拷贝视图:sjson 每次删除都写入新 buffer,视图所指的旧 body + // 不会被修改;删除只发生在 cache_control 内部,数组下标保持不变。 + // 清理 system 数组中的 cache_control - systemArr := gjson.GetBytes(body, "system") - if systemArr.Exists() && systemArr.IsArray() { - for i, item := range systemArr.Array() { - if !item.IsObject() { - continue + systemArr := parseRawJSONView(body).Get("system") + if systemArr.IsArray() { + i := -1 + systemArr.ForEach(func(_, item gjson.Result) bool { + i++ + if cc := item.Get("cache_control"); item.IsObject() && cc.IsObject() { + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("system.%d.cache_control", i), cc, isClaude45) } - cc := item.Get("cache_control") - if !cc.Exists() || !cc.IsObject() { - continue - } - body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("system.%d.cache_control", i), cc, isClaude45) - } + return true + }) } // 清理 messages 中的 cache_control - messages := gjson.GetBytes(body, "messages") - if !messages.Exists() || !messages.IsArray() { + messages := parseRawJSONView(body).Get("messages") + if !messages.IsArray() { return body } - for mi, msg := range messages.Array() { - if !msg.IsObject() { - continue - } + mi := -1 + messages.ForEach(func(_, msg gjson.Result) bool { + mi++ content := msg.Get("content") - if !content.Exists() || !content.IsArray() { - continue + if !msg.IsObject() || !content.IsArray() { + return true } - for ci, block := range content.Array() { - if !block.IsObject() { - continue + ci := -1 + content.ForEach(func(_, block gjson.Result) bool { + ci++ + if cc := block.Get("cache_control"); block.IsObject() && cc.IsObject() { + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("messages.%d.content.%d.cache_control", mi, ci), cc, isClaude45) } - cc := block.Get("cache_control") - if !cc.Exists() || !cc.IsObject() { - continue - } - body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("messages.%d.content.%d.cache_control", mi, ci), cc, isClaude45) - } - } + return true + }) + return true + }) return body } diff --git a/backend/internal/service/bedrock_stream.go b/backend/internal/service/bedrock_stream.go index a7637b64e4..c66bfb2136 100644 --- a/backend/internal/service/bedrock_stream.go +++ b/backend/internal/service/bedrock_stream.go @@ -188,7 +188,8 @@ func (s *GatewayService) handleBedrockStreamingResponse( // extractBedrockChunkData 从 Bedrock EventStream payload 中提取 Claude SSE 事件数据 // Bedrock payload 格式:{"bytes":""} func extractBedrockChunkData(payload []byte) []byte { - b64 := gjson.GetBytes(payload, "bytes").String() + // 零拷贝读取:b64 只在本函数内解码,解码结果写入新 buffer。 + b64 := parseRawJSONView(payload).Get("bytes").String() if b64 == "" { return nil } diff --git a/backend/internal/service/hot_path_zero_copy_test.go b/backend/internal/service/hot_path_zero_copy_test.go new file mode 100644 index 0000000000..81295e87ae --- /dev/null +++ b/backend/internal/service/hot_path_zero_copy_test.go @@ -0,0 +1,312 @@ +//go:build unit + +package service + +import ( + "fmt" + "math/rand" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// jsonUEscape spells the six-byte JSON escape backslash, 'u', hex at run time. +func jsonUEscape(hex string) string { return `\` + "u" + hex } + +// referenceNormalizeCompactionTriggerInputOrder always takes the decode path. +func referenceNormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { + if len(body) == 0 { + return body, false, nil + } + var payload map[string]any + if err := decodeOpenAIJSONUseNumber(body, &payload); err != nil { + return body, false, err + } + input, ok := payload["input"].([]any) + if !ok || len(input) == 0 { + return body, false, nil + } + triggerCount := 0 + normalized := make([]any, 0, len(input)) + for _, raw := range input { + item, itemOK := raw.(map[string]any) + if itemOK && item["type"] == "compaction_trigger" { + triggerCount++ + continue + } + normalized = append(normalized, raw) + } + if triggerCount == 0 { + return body, false, nil + } + if triggerCount == 1 { + if last, ok := input[len(input)-1].(map[string]any); ok && last["type"] == "compaction_trigger" { + return body, false, nil + } + } + normalized = append(normalized, map[string]any{"type": "compaction_trigger"}) + payload["input"] = normalized + encoded, err := marshalOpenAIUpstreamJSON(payload) + if err != nil { + return body, false, err + } + return encoded, true, nil +} + +func requireSameCompactionNormalization(t *testing.T, body []byte) { + t.Helper() + got, changed, err := NormalizeCompactionTriggerInputOrder(body) + want, wantChanged, wantErr := referenceNormalizeCompactionTriggerInputOrder(body) + require.Equal(t, wantErr != nil, err != nil, "error mismatch for %s", body) + require.Equal(t, wantChanged, changed, "changed mismatch for %s", body) + require.Equal(t, string(want), string(got), "body mismatch for %s", body) +} + +func TestCompactionTriggerOrderFastPathMatchesDecode(t *testing.T) { + trigger := `{"type":"compaction_trigger"}` + msg := `{"type":"message","role":"user","content":"hi"}` + cases := map[string]string{ + "trigger last": `{"model":"m","input":[` + msg + `,` + trigger + `]}`, + "trigger only": `{"input":[` + trigger + `]}`, + "trigger first": `{"input":[` + trigger + `,` + msg + `]}`, + "two triggers": `{"input":[` + trigger + `,` + msg + `,` + trigger + `]}`, + "token in text, trigger last": `{"input":[{"type":"message","content":"compaction_trigger"},` + trigger + `]}`, + "token only in text": `{"input":[{"type":"message","content":"compaction_trigger"}]}`, + "duplicate input key": `{"input":[` + msg + `,` + trigger + `],"input":[` + msg + `]}`, + "duplicate input key reversed": `{"input":[` + msg + `],"input":[` + msg + `,` + trigger + `]}`, + "duplicate type shadows trigger": `{"input":[` + msg + `,{"type":"compaction_trigger","type":"message"}]}`, + "duplicate type reveals trigger": `{"input":[{"type":"message","type":"compaction_trigger"},` + msg + `]}`, + "escaped trigger last": `{"input":[` + msg + `,{"type":"` + jsonUEscape("0063") + `ompaction_trigger"}]}`, + "escaped key trigger first": `{"input":[{"` + jsonUEscape("0074") + `ype":"compaction_trigger"},` + msg + `]}`, + "non-ascii escape, trigger last": `{"input":[{"type":"message","content":"caf` + jsonUEscape("00e9") + `"},` + trigger + `]}`, + "trigger value not string": `{"input":[` + msg + `,{"type":["compaction_trigger"]}]}`, + "last item not object": `{"input":[` + trigger + `,"compaction"]}`, + "input not array": `{"input":{"type":"compaction_trigger"}}`, + "trailing garbage": `{"input":[` + trigger + `]} x`, + "truncated": `{"input":[` + trigger, + "top-level array": `[{"input":[` + trigger + `]}]`, + "leading whitespace": " \n" + `{"input":[` + msg + `,` + trigger + `]}`, + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + requireSameCompactionNormalization(t, []byte(body)) + }) + } +} + +func TestCompactionTriggerOrderFastPathMatchesDecodeRandomized(t *testing.T) { + rng := rand.New(rand.NewSource(20261114)) + items := []string{ + `{"type":"compaction_trigger"}`, + `{"type":"message","role":"user","content":"hello"}`, + `{"type":"message","content":"mentions compaction_trigger"}`, + `{"type":"compaction_trigger","type":"message"}`, + `{"type":"message","type":"compaction_trigger"}`, + `{"type":"` + jsonUEscape("0063") + `ompaction_trigger"}`, + `{"type":"reasoning","encrypted_content":"` + jsonUEscape("001b") + `x"}`, + `"compaction_trigger"`, + `{"type":"function_call_output","output":""}`, + } + for i := 0; i < 20000; i++ { + var parts []string + for n := rng.Intn(5); n >= 0; n-- { + parts = append(parts, items[rng.Intn(len(items))]) + } + body := `{"model":"m","input":[` + strings.Join(parts, ",") + `]` + if rng.Intn(5) == 0 { + body += `,"input":[` + items[rng.Intn(len(items))] + `]` + } + body += `}` + if rng.Intn(20) == 0 { + body = body[:rng.Intn(len(body))] + } + requireSameCompactionNormalization(t, []byte(body)) + } +} + +func TestHasCompactionTriggerInInputLiteralGate(t *testing.T) { + require.True(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"compaction_trigger"}]}`))) + require.True(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"`+jsonUEscape("0063")+`ompaction_trigger"}]}`))) + require.False(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"message","content":"caf`+jsonUEscape("00e9")+`"}]}`))) + require.False(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"message","content":"compaction_trigger"}]}`))) +} + +func TestResponsesInputHasFunctionCallOutputNamed(t *testing.T) { + cases := []struct { + name string + body string + want bool + }{ + {"declared tool only", `{"tools":[{"type":"function","name":"automation_update"}],"input":[{"type":"function_call_output","call_id":"c","name":"other","output":"ok"}]}`, false}, + {"matching output", `{"input":[{"type":"function_call_output","name":"automation_update","output":"x"}]}`, true}, + {"prefix match", `{"input":[{"type":"function_call_output","name":"codex_apps_selected_page_part_1_of_2"}]}`, true}, + {"escaped key", `{"input":[{"` + jsonUEscape("0074") + `ype":"function_call_output","name":"automation_update"}]}`, true}, + {"escaped value", `{"input":[{"type":"function_call_output","name":"` + jsonUEscape("0061") + `utomation_update"}]}`, true}, + {"type not output", `{"input":[{"type":"function_call","name":"automation_update"}]}`, false}, + {"non-object item", `{"input":["function_call_output automation_update"]}`, false}, + {"input not array", `{"input":{"type":"function_call_output","name":"automation_update"}}`, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, ResponsesInputHasFunctionCallOutputNamed([]byte(tc.body), "automation_update", "codex_apps_selected_page_part_")) + }) + } +} + +// referenceOpenAIRequestBodyHasTools is the scan without the literal gate. +func referenceOpenAIRequestBodyHasTools(body []byte) bool { + if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + return true + } + for _, item := range gjson.GetBytes(body, "input").Array() { + if strings.TrimSpace(item.Get("type").String()) != "additional_tools" { + continue + } + if tools := item.Get("tools"); tools.IsArray() && len(tools.Array()) > 0 { + return true + } + } + return false +} + +func TestOpenAIRequestBodyHasToolsMatchesScan(t *testing.T) { + bodies := []string{ + `{"tools":[{"type":"function","name":"f"}],"input":[]}`, + `{"tools":[],"input":[]}`, + `{"tools":[null]}`, + `{"tools":{},"input":"hi"}`, + `{"input":[{"type":"additional_tools","tools":[{"type":"namespace"}]}]}`, + `{"input":[{"type":" additional_tools ","tools":[{"type":"namespace"}]}]}`, + `{"input":[{"type":"additional_tools","tools":[]}]}`, + `{"input":[{"type":"` + jsonUEscape("0061") + `dditional_tools","tools":[1]}]}`, + `{"input":{"type":"additional_tools","tools":[1]}}`, + `{"input":null}`, + `{"input":"additional_tools"}`, + `{"input":[{"type":"message","content":"caf` + jsonUEscape("00e9") + `"}]}`, + } + for _, body := range bodies { + require.Equal(t, referenceOpenAIRequestBodyHasTools([]byte(body)), openAIRequestBodyHasTools([]byte(body)), body) + } +} + +func TestDeleteJSONPathIfPresent(t *testing.T) { + body := []byte(`{"model":"m","stream":true,"messages":[]}`) + got, err := deleteJSONPathIfPresent(body, "metadata") + require.NoError(t, err) + require.Same(t, &body[0], &got[0], "absent path must return the original buffer") + + for _, path := range []string{"model", "stream", "messages"} { + got, err := deleteJSONPathIfPresent(body, path) + require.NoError(t, err) + want, wantErr := sjson.DeleteBytes(body, path) + require.NoError(t, wantErr) + require.Equal(t, string(want), string(got)) + } + require.Equal(t, `{"model":"m","stream":true,"messages":[]}`, string(body)) + + allocs := testing.AllocsPerRun(20, func() { + _, _ = deleteJSONPathIfPresent(body, "provider") + }) + require.Zero(t, allocs) +} + +// referenceSanitizeBedrockCacheControl is the copying implementation. +func referenceSanitizeBedrockCacheControl(body []byte, modelID string) []byte { + isClaude45 := isBedrockClaude45OrNewer(modelID) + systemArr := gjson.GetBytes(body, "system") + if systemArr.Exists() && systemArr.IsArray() { + for i, item := range systemArr.Array() { + if !item.IsObject() { + continue + } + cc := item.Get("cache_control") + if !cc.Exists() || !cc.IsObject() { + continue + } + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("system.%d.cache_control", i), cc, isClaude45) + } + } + messages := gjson.GetBytes(body, "messages") + if !messages.Exists() || !messages.IsArray() { + return body + } + for mi, msg := range messages.Array() { + if !msg.IsObject() { + continue + } + content := msg.Get("content") + if !content.Exists() || !content.IsArray() { + continue + } + for ci, block := range content.Array() { + if !block.IsObject() { + continue + } + cc := block.Get("cache_control") + if !cc.Exists() || !cc.IsObject() { + continue + } + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("messages.%d.content.%d.cache_control", mi, ci), cc, isClaude45) + } + } + return body +} + +func TestSanitizeBedrockCacheControlMatchesCopyingScan(t *testing.T) { + rng := rand.New(rand.NewSource(7)) + ccs := []string{ + `{"type":"ephemeral"}`, + `{"type":"ephemeral","scope":"global"}`, + `{"type":"ephemeral","ttl":"5m"}`, + `{"type":"ephemeral","ttl":"1h","scope":"global"}`, + `{"type":"ephemeral","ttl":"30m"}`, + `"ephemeral"`, + } + block := func() string { + switch rng.Intn(4) { + case 0: + return `"plain"` + case 1: + return `{"type":"text","text":"a"}` + default: + return `{"type":"text","text":"b","cache_control":` + ccs[rng.Intn(len(ccs))] + `}` + } + } + blocks := func() string { + var parts []string + for n := rng.Intn(4); n >= 0; n-- { + parts = append(parts, block()) + } + return "[" + strings.Join(parts, ",") + "]" + } + for i := 0; i < 3000; i++ { + var msgs []string + for n := rng.Intn(4); n >= 0; n-- { + switch rng.Intn(4) { + case 0: + msgs = append(msgs, `{"role":"user","content":"text"}`) + case 1: + msgs = append(msgs, `"not an object"`) + default: + msgs = append(msgs, `{"role":"user","content":`+blocks()+`}`) + } + } + body := `{"system":` + blocks() + `,"messages":[` + strings.Join(msgs, ",") + `]}` + for _, model := range []string{"anthropic.claude-sonnet-4-6", "anthropic.claude-3-5-sonnet-20241022-v2:0"} { + want := referenceSanitizeBedrockCacheControl([]byte(body), model) + got := sanitizeBedrockCacheControl([]byte(body), model) + require.Equal(t, string(want), string(got), body) + } + } +} + +func TestExtractBedrockChunkDataReadsEscapedAndPlainBase64(t *testing.T) { + require.Equal(t, "hi", string(extractBedrockChunkData([]byte(`{"bytes":"aGk="}`)))) + require.Equal(t, "?>?", string(extractBedrockChunkData([]byte(`{"bytes":"Pz4\/"}`)))) + require.Nil(t, extractBedrockChunkData([]byte(`{"bytes":""}`))) + require.Nil(t, extractBedrockChunkData([]byte(`{"bytes":"%%%"}`))) + require.Nil(t, extractBedrockChunkData([]byte(`{"other":"aGk="}`))) +} diff --git a/backend/internal/service/json_escape_probe.go b/backend/internal/service/json_escape_probe.go new file mode 100644 index 0000000000..317bbbed7c --- /dev/null +++ b/backend/internal/service/json_escape_probe.go @@ -0,0 +1,71 @@ +package service + +import "bytes" + +// JSONMayEscapePlainASCII reports whether body contains a \u escape that spells a +// printable ASCII character no JSON encoder needs to escape (letters, digits, +// underscore, most punctuation). Only such an escape can hide a keyword made of +// those characters from a literal byte search, so when this returns false a +// bytes.Contains miss for such a keyword is a reliable negative. Keywords that +// contain an ignored character below need their own check. +// +// Escapes that encoders do emit on real traffic are ignored: control +// characters (the ANSI escape in shell output), quote, backslash, apostrophe, +// Go's HTML-safe escapes of <, > and &, and every non-ASCII rune. Large agent +// requests therefore keep their fast paths instead of being fully decoded. A +// malformed or truncated escape is reported as true to stay conservative. +// +// Escapes are consumed pairwise, so an escaped backslash followed by a literal +// u (Windows paths, regexes, code samples) is plain text, not an escape. +func JSONMayEscapePlainASCII(body []byte) bool { + for i := 0; ; { + j := bytes.IndexByte(body[i:], '\\') + if j < 0 { + return false + } + next := i + j + 1 + if next >= len(body) { + return true + } + if body[next] != 'u' { + i = next + 1 + continue + } + if next+5 > len(body) { + return true + } + r, ok := parseJSONHex4(body[next+1 : next+5]) + if !ok || jsonEscapeHidesPlainASCII(r) { + return true + } + i = next + 5 + } +} + +func parseJSONHex4(b []byte) (rune, bool) { + var r rune + for _, c := range b { + switch { + case c >= '0' && c <= '9': + r = r<<4 | rune(c-'0') + case c >= 'a' && c <= 'f': + r = r<<4 | rune(c-'a'+10) + case c >= 'A' && c <= 'F': + r = r<<4 | rune(c-'A'+10) + default: + return 0, false + } + } + return r, true +} + +func jsonEscapeHidesPlainASCII(r rune) bool { + if r < 0x20 || r >= 0x7f { + return false + } + switch r { + case '"', '\\', '<', '>', '&', '\'': + return false + } + return true +} diff --git a/backend/internal/service/json_escape_probe_test.go b/backend/internal/service/json_escape_probe_test.go new file mode 100644 index 0000000000..46b1f1d6d7 --- /dev/null +++ b/backend/internal/service/json_escape_probe_test.go @@ -0,0 +1,38 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestJSONMayEscapePlainASCII(t *testing.T) { + // U(hex) spells the six-byte JSON escape backslash, 'u', hex. + U := func(hex string) string { return `\` + "u" + hex } + cases := []struct { + name string + body string + want bool + }{ + {"no escapes", `{"input":[{"type":"message","content":"hi"}]}`, false}, + {"ansi control escape from shell output", `{"output":"` + U("001b") + `[31mred` + U("001b") + `[0m"}`, false}, + {"go html-safe escapes", `{"text":"a ` + U("003c") + ` b ` + U("0026") + ` c ` + U("003e") + ` d"}`, false}, + {"quote apostrophe and backslash escapes", `{"text":"` + U("0022") + U("0027") + U("005c") + `"}`, false}, + {"non-ascii and surrogate pair", `{"text":"caf` + U("00e9") + ` ` + U("d83d") + U("de00") + ` ` + U("4e2d") + `"}`, false}, + {"escaped letter hides a keyword", `{"type":"` + U("0063") + `ompaction_trigger"}`, true}, + {"upper-case hex escaped underscore", `{"type":"input` + U("005F") + `image"}`, true}, + {"escaped digit", `{"n":"` + U("0031") + `"}`, true}, + {"escaped backslash before u is literal text", `{"code":"\` + U("0041") + `"}`, false}, + {"escaped backslash in a path", `{"cwd":"C:\\users\\dev","re":"\\u{1F600}"}`, false}, + {"escape after an escaped backslash", `{"t":"\\` + U("0063") + `"}`, true}, + {"truncated escape", `{"t":"` + U("00"), true}, + {"invalid hex", `{"t":"` + U("ZZZZ") + `"}`, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, JSONMayEscapePlainASCII([]byte(tc.body))) + }) + } +} diff --git a/backend/internal/service/openai_call_output_probe.go b/backend/internal/service/openai_call_output_probe.go new file mode 100644 index 0000000000..ff82ea8eb5 --- /dev/null +++ b/backend/internal/service/openai_call_output_probe.go @@ -0,0 +1,35 @@ +package service + +import ( + "strings" + + "github.com/tidwall/gjson" +) + +// ResponsesInputHasFunctionCallOutputNamed reports whether the top-level input +// array holds an object item whose type is "function_call_output" and whose +// name starts with one of namePrefixes. Keys and string values are compared +// after JSON unescaping, through a zero-copy view of body. When a member is +// duplicated, the first occurrence is read; callers that decode the body +// treat duplicate members separately. +func ResponsesInputHasFunctionCallOutputNamed(body []byte, namePrefixes ...string) bool { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return false + } + found := false + input.ForEach(func(_, item gjson.Result) bool { + if !item.IsObject() || item.Get("type").String() != "function_call_output" { + return true + } + name := item.Get("name").String() + for _, prefix := range namePrefixes { + if strings.HasPrefix(name, prefix) { + found = true + return false + } + } + return true + }) + return found +} diff --git a/backend/internal/service/openai_compact_body_signal.go b/backend/internal/service/openai_compact_body_signal.go index a545f1cfd6..f570d3303b 100644 --- a/backend/internal/service/openai_compact_body_signal.go +++ b/backend/internal/service/openai_compact_body_signal.go @@ -67,16 +67,46 @@ func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { return encoded, true, nil } -// compactionTriggerNeedsDecode lets bodies that cannot hold a trigger skip the -// full decode: the type string appears literally unless a \u escape spells it. -// Such a body must still be a valid JSON object, so decode errors keep -// surfacing from the original path. +var compactionTriggerToken = []byte("compaction_trigger") + +// compactionTriggerNeedsDecode lets bodies whose input order cannot change +// skip the full decode. Without a \u escape that spells plain ASCII, every +// decoded "compaction_trigger" string is a literal occurrence of the token, so: +// - no occurrence means no trigger; +// - a single occurrence that is the type of the last input item, as read +// through the zero-copy view, means the decoder sees either that same item +// as the only trigger or, when a duplicate member shadows it, no trigger. +// +// Either way the body is returned unchanged. Such a body must still be a valid +// JSON object, so decode errors keep surfacing from the original path. func compactionTriggerNeedsDecode(body []byte) bool { - if bytes.Contains(body, []byte("compaction_trigger")) || bytes.Contains(body, []byte(`\u`)) { + if JSONMayEscapePlainASCII(body) { return true } - trimmed := bytes.TrimLeft(body, " \t\r\n") - return len(trimmed) == 0 || trimmed[0] != '{' || !gjson.ValidBytes(body) + switch bytes.Count(body, compactionTriggerToken) { + case 0: + trimmed := bytes.TrimLeft(body, " \t\r\n") + return len(trimmed) == 0 || trimmed[0] != '{' || !gjson.ValidBytes(body) + case 1: + return !compactionTriggerIsLastInputItem(body) || !gjson.ValidBytes(body) + default: + return true + } +} + +// compactionTriggerIsLastInputItem reports whether the last element of the +// top-level input array is an object whose type is "compaction_trigger". +func compactionTriggerIsLastInputItem(body []byte) bool { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return false + } + var last gjson.Result + input.ForEach(func(_, item gjson.Result) bool { + last = item + return true + }) + return last.IsObject() && last.Get("type").String() == "compaction_trigger" } func isOpenAINativeCompactionV2(c *gin.Context) bool { @@ -177,12 +207,17 @@ func applyOpenAICodexBetaFeatures(c *gin.Context, account *Account, h http.Heade // HasCompactionTriggerInInput detects an input item with // type="compaction_trigger". The handler combines this body signal with the // request path and stream flag to distinguish the native remote compaction v2 -// wire from the legacy /responses/compact bridge. +// wire from the legacy /responses/compact bridge. The type string appears +// literally unless a \u escape spells plain ASCII, so other bodies skip the +// structural scan. func HasCompactionTriggerInInput(body []byte) bool { if len(body) == 0 { return false } - input := gjson.GetBytes(body, "input") + if !bytes.Contains(body, compactionTriggerToken) && !JSONMayEscapePlainASCII(body) { + return false + } + input := parseRawJSONView(body).Get("input") if !input.IsArray() { return false } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b7e4514405..ea449fbf35 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -653,19 +653,43 @@ func normalizeOpenAIParallelToolCallsWithoutTools(body []byte, responsesLite boo } // openAIRequestBodyHasTools 同时识别顶层 tools 和 input[].additional_tools。 +// additional_tools 类型字符串只有在字面出现、或被能拼出可见 ASCII 的 \u 转义 +// 拼出时才可能匹配,其余请求体跳过对 input 的结构扫描。 func openAIRequestBodyHasTools(body []byte) bool { - if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + root := parseRawJSONView(body) + if gjsonArrayHasElements(root.Get("tools")) { return true } - for _, item := range gjson.GetBytes(body, "input").Array() { - if strings.TrimSpace(item.Get("type").String()) != "additional_tools" { - continue - } - if tools := item.Get("tools"); tools.IsArray() && len(tools.Array()) > 0 { - return true - } + if !bytes.Contains(body, []byte("additional_tools")) && !JSONMayEscapePlainASCII(body) { + return false } - return false + found := false + isAdditionalToolsWithTools := func(item gjson.Result) bool { + return strings.TrimSpace(item.Get("type").String()) == "additional_tools" && gjsonArrayHasElements(item.Get("tools")) + } + input := root.Get("input") + if !input.IsArray() { + // gjson 把非数组的值当作只含它自身的数组。 + return input.Type != gjson.Null && isAdditionalToolsWithTools(input) + } + input.ForEach(func(_, item gjson.Result) bool { + found = isAdditionalToolsWithTools(item) + return !found + }) + return found +} + +// gjsonArrayHasElements 不分配结果切片地判断数组是否非空。 +func gjsonArrayHasElements(value gjson.Result) bool { + if !value.IsArray() { + return false + } + nonEmpty := false + value.ForEach(func(_, _ gjson.Result) bool { + nonEmpty = true + return false + }) + return nonEmpty } // normalizeOpenAIResponsesReasoningContentReplay removes non-portable @@ -2489,7 +2513,7 @@ func openAIRequestBodyMayContainEmptyBase64InputImage(body []byte) bool { if len(body) == 0 || !openAIRequestBodyMayContainInputImageToken(body) { return false } - input := gjson.GetBytes(body, "input") + input := parseRawJSONView(body).Get("input") if !input.Exists() { return false } @@ -2500,8 +2524,9 @@ func openAIRequestBodyMayContainInputImageToken(body []byte) bool { if bytes.Contains(body, []byte("input_image")) { return true } - // JSON 字符串任意字符都可能被 unicode escape,遇到 \u 时交给 gjson 解码后的结构扫描兜底。 - return bytes.Contains(body, []byte("\\u")) + // JSON 字符串任意字符都可能被 unicode escape;只有能拼出可见 ASCII 字符的 \u + // 才可能藏住 input_image,此时交给 gjson 解码后的结构扫描兜底。 + return JSONMayEscapePlainASCII(body) } func openAIJSONValueMayContainEmptyBase64InputImage(value gjson.Result) bool { diff --git a/backend/internal/service/openai_reasoning_effort_policy.go b/backend/internal/service/openai_reasoning_effort_policy.go index b8f7f3b409..fa023101cf 100644 --- a/backend/internal/service/openai_reasoning_effort_policy.go +++ b/backend/internal/service/openai_reasoning_effort_policy.go @@ -111,11 +111,13 @@ func IsReasoningEffortPolicyDenied(err error) bool { return errors.As(err, &mappingDenied) } +var reasoningEffortSeparatorRemover = strings.NewReplacer("-", "", "_", "", " ", "") + // NormalizeMaxReasoningEffort validates and canonicalizes a group policy value. // Empty means that the group does not impose a ceiling. func NormalizeMaxReasoningEffort(raw string) string { value := strings.ToLower(strings.TrimSpace(raw)) - value = strings.NewReplacer("-", "", "_", "", " ", "").Replace(value) + value = reasoningEffortSeparatorRemover.Replace(value) switch value { case "": return "" diff --git a/backend/internal/service/openai_responses_namespace.go b/backend/internal/service/openai_responses_namespace.go index 17ee436064..3978518ed9 100644 --- a/backend/internal/service/openai_responses_namespace.go +++ b/backend/internal/service/openai_responses_namespace.go @@ -120,7 +120,8 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool { return found } - if hasNamespaceTool(gjson.GetBytes(body, "tools")) { + root := parseRawJSONView(body) + if hasNamespaceTool(root.Get("tools")) { return true } @@ -128,7 +129,7 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool { // tools and into an input.additional_tools carrier. API-key requests are // intentionally not rewritten by normalizeOpenAIResponsesLiteTools, so the // declaration can arrive here only in this form. - input := gjson.GetBytes(body, "input") + input := root.Get("input") if !input.IsArray() { return false } @@ -196,7 +197,9 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo if !bytes.Contains(body, []byte(`"namespace"`)) { return body, nil } - input := gjson.GetBytes(body, "input") + // Zero-copy view: input.Raw aliases body and is only read below; the + // rebuilt array is written into a fresh buffer. + input := parseRawJSONView(body).Get("input") if !input.IsArray() { return body, nil } From b6c21cd5e75acfab663a5b916572d9ed56c70d8a Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 15 Oct 2026 01:26:50 +0800 Subject: [PATCH 69/85] =?UTF-8?q?fix(gemini):=20=E5=8E=9F=E7=94=9F?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E6=8C=89=E7=A8=B3=E5=AE=9A=E5=89=8D=E7=BC=80?= =?UTF-8?q?=E7=94=9F=E6=88=90=E7=B2=98=E6=80=A7=E4=BC=9A=E8=AF=9D=E5=93=88?= =?UTF-8?q?=E5=B8=8C=EF=BC=8C=E6=8D=A2=E5=8F=B7=E6=8C=89=E4=B8=8A=E6=B8=B8?= =?UTF-8?q?=E5=AE=9E=E9=99=85=E7=94=A8=E9=87=8F=E8=AE=A1=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 非 Gemini CLI 客户端的粘性哈希此前取 IP + UA + Key + system + 全部 contents 文本,每轮都变,Redis 绑定在后续轮次永远查不到;只有进程内摘要链能把"完整包含 上一次请求"的纯追加对话留在原号。末尾内容每轮改写(引导/备注)或编辑最后一条 消息的对话每轮都落到不同账号,Vertex 隐式缓存按项目隔离,因此几乎不命中 - 改为 API Key + 模型(渠道映射前)+ tools + systemInstruction + 第一条 user contents 的 parts,取法与 OpenAI 内容兜底 deriveOpenAIContentSessionSeed 一致, 另加 API Key 隔离租户;JSON 规范化后用 xxhash 流式计算,输出与 DeriveSessionHashFromSeed 相同 - 第一条 user 指 role 为 user 或省略的第一条 contents,跳过它之前的 model 开场白; 其 parts 没有有效内容(非空白 text 或带字段的其他 part)时不建立粘性 - Gemini CLI 会话标识仍优先;引用显式缓存的请求仍不参与粘性;摘要链兜底保留, 只在没有绑定时运行 - 粘性会话换号时不再强制缓存计费:此前整段 input 按缓存读取计费,而新账号上游 按全价收取,原号上本就不会命中的新增末尾也被一并打折;粘性生效后绑定请求大幅 增加,该补偿的覆盖面随之扩大。现按上游实际返回的用量计费,缓存读取只来自 cachedContentTokenCount --- .../internal/handler/gemini_v1beta_handler.go | 17 +-- backend/internal/service/gemini_session.go | 90 ++++++++++++ .../internal/service/gemini_session_test.go | 137 ++++++++++++++++++ 3 files changed, 230 insertions(+), 14 deletions(-) diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 06e2472f8d..71e1af1371 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -13,7 +13,6 @@ import ( "strconv" "strings" - "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" "github.com/Wei-Shaw/sub2api/internal/pkg/gemini" "github.com/Wei-Shaw/sub2api/internal/pkg/googleapi" @@ -468,16 +467,8 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { sessionHash = extractGeminiCLISessionHash(c, body) } if sessionHash == "" && cachedContentBinding == nil { - // Fallback: 使用通用的会话哈希生成逻辑(适用于其他客户端) - parsedReq, _ := service.ParseGatewayRequest(service.NewRequestBodyRef(body), domain.PlatformGemini) - if parsedReq != nil { - parsedReq.SessionContext = &service.SessionContext{ - ClientIP: ip.GetClientIP(c), - UserAgent: c.GetHeader("User-Agent"), - APIKeyID: apiKey.ID, - } - } - sessionHash = h.gatewayService.GenerateSessionHash(parsedReq) + // 其他客户端:按 API Key + 模型 + tools + systemInstruction + 第一条 user contents 的 parts 生成内容哈希 + sessionHash = service.GenerateGeminiContentSessionHash(apiKey.ID, reqModel, body) } sessionKey := sessionHash if sessionHash != "" { @@ -825,12 +816,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { requestPayloadHash := service.HashUsageRequestPayload(body) inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) - // ForceCacheBilling 提前拍成标量,避免 worker 闭包保活 failover 状态里的响应体。 - forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) // 长上下文阶梯由目录数据驱动,统一在计费路径内生效,入口无需声明。 channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) + // 按上游实际返回的用量计费:粘性会话换号不做强制缓存计费,缓存读取只来自上游的 cachedContentTokenCount。 h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -845,7 +835,6 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { UserAgent: userAgent, IPAddress: clientIP, RequestPayloadHash: requestPayloadHash, - ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, SessionID: sessionID, ChannelUsageFields: channelUsageFields, diff --git a/backend/internal/service/gemini_session.go b/backend/internal/service/gemini_session.go index cd29132801..e882f299ca 100644 --- a/backend/internal/service/gemini_session.go +++ b/backend/internal/service/gemini_session.go @@ -4,13 +4,103 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" + "fmt" "strconv" "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" "github.com/cespare/xxhash/v2" + "github.com/tidwall/gjson" ) +// geminiContentSessionSeedPrefix 区分 Gemini 内容派生的会话种子与其他来源的种子。 +const geminiContentSessionSeedPrefix = "gemini_cs_" + +// GenerateGeminiContentSessionHash 生成 Gemini 原生请求的内容粘性会话哈希。 +// 种子由 API Key、模型、tools、systemInstruction 与第一条 user contents 的 parts 组成, +// 后四项的取法与 OpenAI 内容兜底(deriveOpenAIContentSessionSeed)一致,API Key 用于隔离租户。 +// 这些字段不变时,末尾追加、改写或替换 contents 都不改变哈希;字段全部相同的不同会话共享同一哈希。 +// systemInstruction 与 system_instruction 同时存在时取前者。 +// 找不到第一条 user contents(role 为 user 或省略),或其 parts 中没有有效 part 时返回空串,不建立粘性。 +func GenerateGeminiContentSessionHash(apiKeyID int64, model string, body []byte) string { + root := parseRawJSONView(body) + if !root.IsObject() { + return "" + } + firstUserParts := firstGeminiUserParts(root.Get("contents")) + if !firstUserParts.Exists() { + return "" + } + + d := xxhash.New() + _, _ = d.WriteString(geminiContentSessionSeedPrefix) + _, _ = d.WriteString("key=") + _, _ = d.WriteString(strconv.FormatInt(apiKeyID, 10)) + if model = strings.TrimSpace(model); model != "" { + _, _ = d.WriteString("|model=") + _, _ = d.WriteString(model) + } + if tools := root.Get("tools"); tools.IsArray() { + if normalized, ok := normalizeNonEmptyCompatSeedJSON(tools); ok { + _, _ = d.WriteString("|tools=") + _, _ = d.WriteString(normalized) + } + } + system := root.Get("systemInstruction") + if !system.Exists() { + system = root.Get("system_instruction") + } + if normalized, ok := normalizeNonEmptyCompatSeedJSON(system); ok { + _, _ = d.WriteString("|system=") + _, _ = d.WriteString(normalized) + } + _, _ = d.WriteString("|first_user=") + _, _ = d.WriteString(normalizeCompatSeedJSON(json.RawMessage(firstUserParts.Raw))) + return fmt.Sprintf("%016x", d.Sum64()) +} + +// firstGeminiUserParts 返回第一条 user contents(role 为 user 或省略)的 parts,跳过它之前的 +// model 等其他角色;该条不是对象或 parts 中没有有效 part 时返回空结果。 +func firstGeminiUserParts(contents gjson.Result) gjson.Result { + var parts gjson.Result + if !contents.IsArray() { + return parts + } + contents.ForEach(func(_, content gjson.Result) bool { + if content.IsObject() { + if role := content.Get("role").String(); role != "" && role != "user" { + return true + } + if p := content.Get("parts"); hasMeaningfulGeminiParts(p) { + parts = p + } + } + return false + }) + return parts +} + +// hasMeaningfulGeminiParts 判断 parts 中是否至少有一个有效 part:text 去除首尾空白后非空, +// 或是至少含一个字段的其他 part(如 inlineData、fileData)。 +func hasMeaningfulGeminiParts(parts gjson.Result) bool { + if !parts.IsArray() { + return false + } + meaningful := false + parts.ForEach(func(_, part gjson.Result) bool { + if text := part.Get("text"); text.Exists() { + meaningful = strings.TrimSpace(text.String()) != "" + } else if part.IsObject() { + part.ForEach(func(_, _ gjson.Result) bool { + meaningful = true + return false + }) + } + return !meaningful + }) + return meaningful +} + // shortHash 使用 XXHash64 + Base36 生成短 hash(16 字符) // XXHash64 比 SHA256 快约 10 倍,Base36 比 Hex 短约 20% func shortHash(data []byte) string { diff --git a/backend/internal/service/gemini_session_test.go b/backend/internal/service/gemini_session_test.go index 27321996a7..a07e57d9d7 100644 --- a/backend/internal/service/gemini_session_test.go +++ b/backend/internal/service/gemini_session_test.go @@ -405,3 +405,140 @@ func TestGenerateGeminiDigestSessionKey(t *testing.T) { } }) } + +func TestGenerateGeminiContentSessionHash_StableAcrossTurns(t *testing.T) { + const prefix = `"tools":[{"functionDeclarations":[{"name":"lookup","parameters":{"type":"object"}}]}],"systemInstruction":{"parts":[{"text":"You are Aria."}]}` + const first = `{"role":"user","parts":[{"text":"[Story summary] Kim meets Aria."}]},{"role":"model","parts":[{"text":"Noted."}]}` + turn1 := `{` + prefix + `,"contents":[` + first + `,{"role":"user","parts":[{"text":"guide v1"}]},{"role":"user","parts":[{"text":"msg1"},{"text":"notes v1"}]}]}` + appended := `{` + prefix + `,"contents":[` + first + `,{"role":"user","parts":[{"text":"guide v1"}]},{"role":"user","parts":[{"text":"msg1"},{"text":"notes v1"}]},{"role":"model","parts":[{"functionCall":{"name":"lookup","args":{}},"thoughtSignature":"c2ln"}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","response":{}}}]}]}` + turnContext := `{` + prefix + `,"contents":[` + first + `,{"role":"user","parts":[{"text":"msg1"}]},{"role":"model","parts":[{"text":"reply1"}]},{"role":"user","parts":[{"text":"guide v2"}]},{"role":"user","parts":[{"text":"msg2"},{"text":"notes v2"}]}]}` + edited := `{` + prefix + `,"contents":[` + first + `,{"role":"user","parts":[{"text":"guide v1"}]},{"role":"user","parts":[{"text":"msg1 edited"}]}],"generationConfig":{"temperature":0.2}}` + + want := GenerateGeminiContentSessionHash(7, "gemini-4-argon", []byte(turn1)) + if want == "" { + t.Fatal("expected non-empty hash") + } + for name, body := range map[string]string{"appended": appended, "turn_context": turnContext, "edited_last": edited} { + if got := GenerateGeminiContentSessionHash(7, "gemini-4-argon", []byte(body)); got != want { + t.Errorf("%s: hash %q, want %q", name, got, want) + } + } +} + +func TestGenerateGeminiContentSessionHash_SeedFormat(t *testing.T) { + body := `{"tools":[{"googleSearch":{}}],"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"hi"}]}]}` + want := DeriveSessionHashFromSeed(`gemini_cs_key=3|model=gemini-3.8-flash|tools=[{"googleSearch":{}}]|system={"parts":[{"text":"sys"}]}|first_user=[{"text":"hi"}]`) + if got := GenerateGeminiContentSessionHash(3, " gemini-3.8-flash ", []byte(body)); got != want { + t.Fatalf("hash %q, want %q", got, want) + } +} + +func TestGenerateGeminiContentSessionHash_DistinguishesEachSeedField(t *testing.T) { + const ( + tools = `"tools":[{"functionDeclarations":[{"name":"a"}]}],` + system = `"systemInstruction":{"parts":[{"text":"sys A"}]},` + first = `{"role":"user","parts":[{"text":"first A"}]}` + trailing = `,{"role":"model","parts":[{"text":"reply"}]},{"role":"user","parts":[{"text":"tail"}]}` + ) + base := `{` + tools + system + `"contents":[` + first + trailing + `]}` + h := GenerateGeminiContentSessionHash(1, "m1", []byte(base)) + cases := map[string]string{ + "other_key": GenerateGeminiContentSessionHash(2, "m1", []byte(base)), + "other_model": GenerateGeminiContentSessionHash(1, "m2", []byte(base)), + "no_model": GenerateGeminiContentSessionHash(1, "", []byte(base)), + "other_tools": GenerateGeminiContentSessionHash(1, "m1", []byte(`{"tools":[{"functionDeclarations":[{"name":"b"}]}],`+system+`"contents":[`+first+trailing+`]}`)), + "no_tools": GenerateGeminiContentSessionHash(1, "m1", []byte(`{`+system+`"contents":[`+first+trailing+`]}`)), + "other_system": GenerateGeminiContentSessionHash(1, "m1", []byte(`{`+tools+`"systemInstruction":{"parts":[{"text":"sys B"}]},"contents":[`+first+trailing+`]}`)), + "no_system": GenerateGeminiContentSessionHash(1, "m1", []byte(`{`+tools+`"contents":[`+first+trailing+`]}`)), + "other_first": GenerateGeminiContentSessionHash(1, "m1", []byte(`{`+tools+system+`"contents":[{"role":"user","parts":[{"text":"first B"}]}`+trailing+`]}`)), + "inline_first": GenerateGeminiContentSessionHash(1, "m1", []byte(`{`+tools+system+`"contents":[{"role":"user","parts":[{"text":"first A"},{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgo="}}]}`+trailing+`]}`)), + } + for name, got := range cases { + if got == "" { + t.Errorf("%s: expected non-empty hash", name) + } + if got == h { + t.Errorf("%s: hash should differ from base", name) + } + } +} + +func TestGenerateGeminiContentSessionHash_FirstUserSkipsLeadingModelContent(t *testing.T) { + body := func(firstUser string) []byte { + return []byte(`{"systemInstruction":{"parts":[{"text":"You are Aria."}]},"contents":[{"role":"model","parts":[{"text":"Hi! I'm Aria."}]},{"role":"user","parts":[{"text":"` + firstUser + `"}]},{"role":"model","parts":[{"text":"reply"}]},{"role":"user","parts":[{"text":"next"}]}]}`) + } + kim := GenerateGeminiContentSessionHash(1, "m", body("I'm Kim.")) + lee := GenerateGeminiContentSessionHash(1, "m", body("I'm Lee.")) + if kim == "" || lee == "" { + t.Fatal("expected non-empty hashes") + } + if kim == lee { + t.Error("conversations sharing only the leading model greeting should not share a hash") + } + + userFirst := `{"systemInstruction":{"parts":[{"text":"You are Aria."}]},"contents":[{"role":"user","parts":[{"text":"I'm Kim."}]}]}` + if got := GenerateGeminiContentSessionHash(1, "m", []byte(userFirst)); got != kim { + t.Errorf("leading model content should be skipped: hash %q, want %q", got, kim) + } +} + +func TestGenerateGeminiContentSessionHash_RoleOmittedCountsAsUser(t *testing.T) { + withRole := `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}` + withoutRole := `{"contents":[{"parts":[{"text":"hi"}]}]}` + if GenerateGeminiContentSessionHash(1, "m", []byte(withoutRole)) == "" { + t.Fatal("expected non-empty hash when role is omitted") + } + if GenerateGeminiContentSessionHash(1, "m", []byte(withRole)) != GenerateGeminiContentSessionHash(1, "m", []byte(withoutRole)) { + t.Error("omitted role and explicit user role should share a hash") + } +} + +func TestGenerateGeminiContentSessionHash_NonTextPartAnchors(t *testing.T) { + inlineOnly := `{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgo="}}]}]}` + blankThenInline := `{"contents":[{"role":"user","parts":[{"text":" "},{"fileData":{"fileUri":"gs://b/f.pdf"}}]}]}` + for name, body := range map[string]string{"inline_only": inlineOnly, "blank_then_file": blankThenInline} { + if GenerateGeminiContentSessionHash(1, "m", []byte(body)) == "" { + t.Errorf("%s: expected non-empty hash", name) + } + } +} + +func TestGenerateGeminiContentSessionHash_NormalizesJSONFormatting(t *testing.T) { + compact := `{"tools":[{"googleSearch":{}}],"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"first"}]}]}` + reordered := `{ "contents" : [ { "parts" : [ { "text" : "first" } ], "role" : "user" } ], "systemInstruction" : { "parts" : [ { "text" : "sys" } ] }, "tools" : [ { "googleSearch" : { } } ] }` + emptyToolsBase := `{"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"first"}]}]}` + emptyTools := `{"tools":[],"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"first"}]}]}` + if GenerateGeminiContentSessionHash(1, "m", []byte(emptyTools)) != GenerateGeminiContentSessionHash(1, "m", []byte(emptyToolsBase)) { + t.Error("empty tools should hash like missing tools") + } + snakeCase := `{"tools":[{"googleSearch":{}}],"system_instruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"first"}]}]}` + bothSystems := `{"tools":[{"googleSearch":{}}],"system_instruction":{"parts":[{"text":"other"}]},"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"first"}]}]}` + + want := GenerateGeminiContentSessionHash(1, "m", []byte(compact)) + for name, body := range map[string]string{"reordered": reordered, "snake_case_system": snakeCase, "camel_case_system_wins": bothSystems} { + if got := GenerateGeminiContentSessionHash(1, "m", []byte(body)); got != want { + t.Errorf("%s: hash %q, want %q", name, got, want) + } + } +} + +func TestGenerateGeminiContentSessionHash_EmptyWithoutFirstUserContent(t *testing.T) { + for name, body := range map[string]string{ + "empty_body": ``, + "non_object_body": `[1,2]`, + "no_contents": `{"systemInstruction":{"parts":[{"text":"sys"}]}}`, + "contents_object": `{"contents":{"role":"user","parts":[{"text":"hi"}]}}`, + "empty_contents": `{"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[]}`, + "only_model": `{"contents":[{"role":"model","parts":[{"text":"Hi!"}]}]}`, + "empty_parts": `{"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[]}]}`, + "missing_parts": `{"systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user"}]}`, + "blank_text": `{"contents":[{"role":"user","parts":[{"text":" "}]}]}`, + "empty_part": `{"contents":[{"role":"user","parts":[{}]}]}`, + "null_part": `{"contents":[{"role":"user","parts":[null]}]}`, + "non_object_first": `{"contents":["hello",{"role":"user","parts":[{"text":"hi"}]}]}`, + } { + if got := GenerateGeminiContentSessionHash(1, "m", []byte(body)); got != "" { + t.Errorf("%s: expected empty hash, got %q", name, got) + } + } +} From b7878328b699bd5f5b61e10df2db74a3723dfc7a Mon Sep 17 00:00:00 2001 From: r266-tech Date: Sun, 15 Nov 2026 11:43:52 +0800 Subject: [PATCH 70/85] fix(pricing): honor explicit DeepSeek token price overrides --- backend/internal/service/billing_service.go | 56 +++++---- .../internal/service/deepseek_pricing_test.go | 112 ++++++++++++++++++ backend/internal/service/pricing_service.go | 36 +++++- deploy/config.example.yaml | 5 + 4 files changed, 181 insertions(+), 28 deletions(-) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index ca526bd8b6..37340fe652 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -98,15 +98,16 @@ type BillingCache interface { type ModelPricing struct { // UltrafastMultiplier is model-owned and independent of operator Fast pricing. UltrafastMultiplier float64 - InputPricePerToken float64 // 每token输入价格 (USD) - InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD) - ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken - ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价 - OutputPricePerToken float64 // 每token输出价格 (USD) - OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD) - CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD) - CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD) - CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退) + InputPricePerToken float64 // 每token输入价格 (USD) + InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD) + ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken + ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价 + OutputPricePerToken float64 // 每token输出价格 (USD) + OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD) + CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD) + CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD) + CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退) + priceOverrides tokenPriceOverrides CacheReadPricePerToken float64 // 缓存读取每token价格 (USD) CacheReadPricePerTokenPriority float64 // priority service tier 下缓存读取每token价格 (USD) FastMultiplier *float64 // 渠道显式 Fast/priority 倍率;nil 时沿用模型目录行为 @@ -1454,6 +1455,7 @@ func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (* price1h := litellmPricing.CacheCreationInputTokenCostAbove1hr enableBreakdown := price1h > 0 && price1h > price5m return s.applyModelSpecificPricingPolicyEx(model, &ModelPricing{ + priceOverrides: litellmPricing.priceOverrides, InputPricePerToken: litellmPricing.InputCostPerToken, InputPricePerTokenPriority: litellmPricing.InputCostPerTokenPriority, OutputPricePerToken: litellmPricing.OutputCostPerToken, @@ -1676,13 +1678,19 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos // DeepSeek 模型默认价卡按官方峰谷口径调整:高峰时段(01:00–04:00 与 // 06:00–10:00 UTC,仅工作日;北京时间周末全天低谷)按 2× 低谷价计费。 // 仅作用于默认价卡(Source=LiteLLM,无分组/渠道自定义定价)——分组/渠道 - // 自定义定价保持运营者语义,不叠加。先克隆再乘,避免污染共享 fallbackPrices 指针。 + // 自定义定价及 override_file 显式覆盖的字段不叠加。先克隆再乘,避免污染共享价卡。 if resolved.Source == PricingSourceLiteLLM && isDeepSeekModel(input.Model) { if mult := deepseekPeakMultiplierAt(pricingAt); mult > 1 { cloned := *pricing - cloned.InputPricePerToken *= mult - cloned.OutputPricePerToken *= mult - cloned.CacheReadPricePerToken *= mult + if !cloned.priceOverrides.input { + cloned.InputPricePerToken *= mult + } + if !cloned.priceOverrides.output { + cloned.OutputPricePerToken *= mult + } + if !cloned.priceOverrides.cacheRead { + cloned.CacheReadPricePerToken *= mult + } pricing = &cloned } } @@ -1986,7 +1994,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing if pricing == nil { return nil } - // DeepSeek 模型:无论 JSON/远端价格表给什么价,一律强制官方低谷价 + // DeepSeek 模型:目录/回退数据使用官方低谷价;override_file 显式覆盖的字段保留。 // (Flash 三档为 2026-09-10 官方降价后口径)。这是覆盖远端旧价的关键——远端 // 仓库不可改,生产会先拉到旧价,必须在此兜底修正;克隆后再覆盖,避免污染 // 共享 fallbackPrices 指针。 @@ -1997,16 +2005,18 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing // 对默认价卡另行叠加(分组/渠道自定义定价不叠加)。 if forceDeepSeekRates && isDeepSeekModel(model) { cloned := *pricing + inputPrice, outputPrice, cacheReadPrice := deepseekFlashOffPeakInputPrice, deepseekFlashOffPeakOutputPrice, deepseekFlashOffPeakCacheRead if isDeepSeekProModel(model) { - cloned.InputPricePerToken = deepseekProOffPeakInputPrice - cloned.OutputPricePerToken = deepseekProOffPeakOutputPrice - cloned.CacheReadPricePerToken = deepseekProOffPeakCacheRead - } else { - // deepseek-flash(= V4.1-Flash)、deepseek-v4-flash / - // deepseek-v4-flash-vision-exp 与其余 deepseek-* 共用 flash 价。 - cloned.InputPricePerToken = deepseekFlashOffPeakInputPrice - cloned.OutputPricePerToken = deepseekFlashOffPeakOutputPrice - cloned.CacheReadPricePerToken = deepseekFlashOffPeakCacheRead + inputPrice, outputPrice, cacheReadPrice = deepseekProOffPeakInputPrice, deepseekProOffPeakOutputPrice, deepseekProOffPeakCacheRead + } + if !cloned.priceOverrides.input { + cloned.InputPricePerToken = inputPrice + } + if !cloned.priceOverrides.output { + cloned.OutputPricePerToken = outputPrice + } + if !cloned.priceOverrides.cacheRead { + cloned.CacheReadPricePerToken = cacheReadPrice } return &cloned } diff --git a/backend/internal/service/deepseek_pricing_test.go b/backend/internal/service/deepseek_pricing_test.go index 4f7f8b6f49..e11c6265d0 100644 --- a/backend/internal/service/deepseek_pricing_test.go +++ b/backend/internal/service/deepseek_pricing_test.go @@ -442,3 +442,115 @@ func TestCalculateCostUnified_DeepseekProRetainsRatesAfterSeptember14(t *testing require.InDelta(t, proTotal, versioned.TotalCost, 1e-10, "versioned pro names must retain Pro rates on September 14") } + +// Explicit override-file token prices are final operator rates, including zero. +// Fields absent from that patch still use the official default and peak policy. +func TestDeepseekOverrideFileTokenPrices(t *testing.T) { + type prices struct{ input, output, cacheRead float64 } + official := prices{1.5e-7, 6e-7, 3e-9} + officialPeak := prices{3e-7, 1.2e-6, 6e-9} + custom := prices{2e-6, 3e-6, 4e-7} + fullPatch := `{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0.0000004}` + cases := []struct { + name, model, layer, patch string + offPeak, peak prices + }{ + {"flash full", "deepseek-flash", "catalog", fullPatch, custom, custom}, + {"pro full", "deepseek-v4-pro", "catalog", fullPatch, custom, custom}, + {"versioned pro full", "deepseek-v4-pro-0813", "catalog", fullPatch, custom, custom}, + {"fallback full", "deepseek-flash", "fallback", fullPatch, custom, custom}, + {"custom model override only", "deepseek-custom", "override", fullPatch, custom, custom}, + {"override only", "deepseek-flash", "override", fullPatch, custom, custom}, + {"input only", "deepseek-flash", "catalog", `{"input_cost_per_token":0.000002}`, prices{2e-6, 6e-7, 3e-9}, prices{2e-6, 1.2e-6, 6e-9}}, + {"zero input", "deepseek-flash", "catalog", `{"input_cost_per_token":0}`, prices{0, 6e-7, 3e-9}, prices{0, 1.2e-6, 6e-9}}, + {"zero output", "deepseek-flash", "catalog", `{"output_cost_per_token":0}`, prices{1.5e-7, 0, 3e-9}, prices{3e-7, 0, 6e-9}}, + {"zero cache read", "deepseek-flash", "catalog", `{"cache_read_input_token_cost":0}`, prices{1.5e-7, 6e-7, 0}, prices{3e-7, 1.2e-6, 0}}, + {"metadata only", "deepseek-flash", "catalog", `{"supports_prompt_caching":true}`, official, officialPeak}, + {"null input", "deepseek-flash", "catalog", `{"input_cost_per_token":null}`, official, officialPeak}, + {"negative input", "deepseek-flash", "catalog", `{"input_cost_per_token":-0.000002}`, official, officialPeak}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + cfg := &config.Config{} + cfg.Pricing.DataDir = dir + cfg.Pricing.OverrideFile = filepath.Join(dir, "overrides.json") + require.NoError(t, os.WriteFile(cfg.Pricing.OverrideFile, []byte(`{"`+tc.model+`":`+tc.patch+`}`), 0644)) + // Deliberately stale catalog rates must still be corrected for every + // field that the operator did not explicitly override. + catalog := []byte(`{"` + tc.model + `":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002,"cache_read_input_token_cost":0.000001}}`) + if tc.layer == "fallback" { + cfg.Pricing.FallbackFile = filepath.Join(dir, "fallback.json") + require.NoError(t, os.WriteFile(cfg.Pricing.FallbackFile, catalog, 0644)) + } + if tc.layer != "catalog" { + catalog = []byte(`{"other-model":{"input_cost_per_token":0.000001}}`) + } + svc := &PricingService{cfg: cfg} + require.NoError(t, os.WriteFile(svc.getPricingFilePath(), catalog, 0644)) + require.NoError(t, svc.loadPricingData(svc.getPricingFilePath())) + billing := NewBillingService(cfg, svc) + resolver := NewModelPricingResolver(nil, billing) + tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000} + for _, slot := range []struct { + name string + at time.Time + want prices + }{ + {"off peak", time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC), tc.offPeak}, + {"peak", time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC), tc.peak}, + } { + t.Run(slot.name, func(t *testing.T) { + cost, err := billing.CalculateCostUnified(CostInput{ + Ctx: context.Background(), Model: tc.model, Tokens: tokens, RateMultiplier: 1.25, + Resolver: resolver, PricingAt: slot.at, + }) + require.NoError(t, err) + require.InDelta(t, 1000*slot.want.input, cost.InputCost, 1e-12) + require.InDelta(t, 500*slot.want.output, cost.OutputCost, 1e-12) + require.InDelta(t, 2000*slot.want.cacheRead, cost.CacheReadCost, 1e-12) + want := 1000*slot.want.input + 500*slot.want.output + 2000*slot.want.cacheRead + require.InDelta(t, want, cost.TotalCost, 1e-12) + require.InDelta(t, want*1.25, cost.ActualCost, 1e-12) + stats := tryModelFilePricing(billing, tc.model, tokens, "", slot.at, false) + require.NotNil(t, stats) + require.InDelta(t, want, *stats, 1e-12, "account statistics use the same override rates") + }) + } + // Catalog lookup and legacy estimates also retain the override. + pricing, err := billing.GetModelPricing(tc.model) + require.NoError(t, err) + require.InDelta(t, tc.offPeak.input, pricing.InputPricePerToken, 1e-15) + require.InDelta(t, tc.offPeak.output, pricing.OutputPricePerToken, 1e-15) + require.InDelta(t, tc.offPeak.cacheRead, pricing.CacheReadPricePerToken, 1e-15) + estimate, err := billing.CalculateCost(tc.model, tokens, 1) + require.NoError(t, err) + want := 1000*tc.offPeak.input + 500*tc.offPeak.output + 2000*tc.offPeak.cacheRead + require.InDelta(t, want, estimate.TotalCost, 1e-12) + }) + } +} + +func TestDeepseekOverrideFileReloadRestoresOfficialPolicy(t *testing.T) { + svc := newHotReloadPricingService(t, `{"deepseek-flash":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002}}`, + `{"deepseek-flash":{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0}}`) + billing := NewBillingService(svc.cfg, svc) + resolver := NewModelPricingResolver(nil, billing) + check := func(wantInput, wantOutput, wantCacheRead float64) { + t.Helper() + cost, err := billing.CalculateCostUnified(CostInput{Ctx: context.Background(), Model: "deepseek-flash", + Tokens: UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000}, RateMultiplier: 1, + Resolver: resolver, PricingAt: time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC)}) + require.NoError(t, err) + require.InDelta(t, wantInput, cost.InputCost, 1e-12) + require.InDelta(t, wantOutput, cost.OutputCost, 1e-12) + require.InDelta(t, wantCacheRead, cost.CacheReadCost, 1e-12) + } + check(0.002, 0.0015, 0) + require.NoError(t, os.WriteFile(svc.cfg.Pricing.OverrideFile, []byte(`{"deepseek-flash":{"output_cost_per_token":0}}`), 0644)) + svc.reloadIfCustomFilesChanged() + check(0.0003, 0, 0.000012) + require.NoError(t, os.Remove(svc.cfg.Pricing.OverrideFile)) + svc.reloadIfCustomFilesChanged() + check(0.0003, 0.0006, 0.000012) +} diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index f973b5abef..310a044f06 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -232,10 +232,17 @@ var ( } ) +// tokenPriceOverrides tracks explicit nonnegative rates from pricing.override_file. +// Keep this provenance with the parsed card so billing never rereads the file. +type tokenPriceOverrides struct { + input, output, cacheRead bool +} + // LiteLLMModelPricing LiteLLM价格数据结构 // 只保留我们需要的字段,使用指针来处理可能缺失的值 type LiteLLMModelPricing struct { - CacheCreationInputTokenCostExplicit bool `json:"-"` + CacheCreationInputTokenCostExplicit bool `json:"-"` + priceOverrides tokenPriceOverrides InputCostPerToken float64 `json:"input_cost_per_token"` InputCostPerTokenPriority float64 `json:"input_cost_per_token_priority"` OutputCostPerToken float64 `json:"output_cost_per_token"` @@ -686,7 +693,7 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel if err := json.Unmarshal(body, &rawData); err != nil { return nil, fmt.Errorf("parse raw JSON: %w", err) } - rawData = s.applyPricingOverrides(rawData) + rawData, priceOverrides := s.applyPricingOverrides(rawData) result := make(map[string]*LiteLLMModelPricing) skipped := 0 @@ -711,6 +718,7 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel } pricing := &LiteLLMModelPricing{ + priceOverrides: priceOverrides[modelName], LiteLLMProvider: entry.LiteLLMProvider, Mode: entry.Mode, SupportsPromptCaching: entry.SupportsPromptCaching, @@ -951,11 +959,12 @@ func warnOrphanCacheTierFields(entries []string) { // 文件的解析都经过 parsePricingData,因此 override 是最高优先级的数据源。这里只修补 // 已存在的条目:目录/回退里都没有的模型由 mergeOverrideOnlyModels 在两层数据合并后 // 统一并入——若在此处抢先建条目,纯 override 条目会挡住回退文件中同名完整条目的合并。 -func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessage) map[string]json.RawMessage { +func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessage) (map[string]json.RawMessage, map[string]tokenPriceOverrides) { overrides := s.loadPricingOverrideEntries() if len(overrides) == 0 { - return rawData + return rawData, nil } + priceOverrides := make(map[string]tokenPriceOverrides, len(overrides)) for name, patch := range overrides { base, ok := rawData[name] if !ok { @@ -967,8 +976,25 @@ func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessag continue } rawData[name] = merged + priceOverrides[name] = tokenPriceOverridesFromPatch(patch) + } + return rawData, priceOverrides +} + +func tokenPriceOverridesFromPatch(patch json.RawMessage) tokenPriceOverrides { + var fields map[string]json.RawMessage + if json.Unmarshal(patch, &fields) != nil { + return tokenPriceOverrides{} + } + explicitRate := func(field string) bool { + var rate *float64 + return json.Unmarshal(fields[field], &rate) == nil && rate != nil && *rate >= 0 + } + return tokenPriceOverrides{ + input: explicitRate("input_cost_per_token"), + output: explicitRate("output_cost_per_token"), + cacheRead: explicitRate("cache_read_input_token_cost"), } - return rawData } // loadPricingOverrideEntries 读取 override 文件的原始条目。未配置返回 nil; diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 2c6859ec0d..2b9724295b 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -1155,6 +1155,11 @@ pricing: # Gemini 显式缓存存储单价(每 token 每小时,USD)优先取这里的 cache_storage_cost_per_token_per_hour 字段, # 未配置时使用内置官方价(先按已发布型号,再按 Pro / Flash 系列兜底);两者都没有的模型拒绝创建缓存。 # 目录中不存在的模型条目还须同时提供 input_cost_per_token / output_cost_per_token。 + # Explicit nonnegative DeepSeek input/output/cache-read token prices here, + # including zero, are final rates and do not receive the official peak multiplier. + # Omitted or null fields still use the official defaults and peak/off-peak rules. + # DeepSeek 的输入/输出/缓存读单价若在此显式设为非负值(含 0),按该价计费, + # 不叠加官方高峰倍率;省略或 null 的字段仍按官方默认价与峰谷规则计费。 # override_file: "./data/model_pricing_overrides.json" # Update interval in hours # 更新间隔(小时) From d3716a1730e81ba53fd9011ae6091b670a72f6df Mon Sep 17 00:00:00 2001 From: William Drake Date: Sat, 14 Nov 2026 20:43:58 -0700 Subject: [PATCH 71/85] test(antigravity): a committed empty compat stream should release the session's sticky account --- ...ravity_compat_committed_no_content_test.go | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 backend/internal/service/antigravity_compat_committed_no_content_test.go diff --git a/backend/internal/service/antigravity_compat_committed_no_content_test.go b/backend/internal/service/antigravity_compat_committed_no_content_test.go new file mode 100644 index 0000000000..c7887840a1 --- /dev/null +++ b/backend/internal/service/antigravity_compat_committed_no_content_test.go @@ -0,0 +1,98 @@ +package service + +import ( + "context" + "errors" + "io" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// runCompatStreamToEnd drives the compat stream handler with an upstream that +// sends nothing and closes after closeAfter. +func runCompatStreamToEnd(t *testing.T, keepaliveInterval, maxWait, closeAfter time.Duration) error { + t.Helper() + svc := newAntigravityCompatService(config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 30, StreamKeepaliveInterval: 0, + }, nil) + c, _ := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nil) + reader, pipeWriter := io.Pipe() + defer func() { _ = reader.Close() }() + resp := &http.Response{StatusCode: http.StatusOK, Body: reader} + done := make(chan error, 1) + go func() { + _, err := svc.handleAntigravityCompatStreamWithKeepaliveInterval( + c, resp, time.Now(), "gemini-4-hydrogen-high", + newAntigravityResponsesStreamAdapter("gemini-4-hydrogen-high"), "test", keepaliveInterval, maxWait, + ) + done <- err + }() + time.Sleep(closeAfter) + _ = pipeWriter.Close() + select { + case err := <-done: + return err + case <-time.After(2 * time.Second): + t.Fatal("compat stream handler did not return") + return nil + } +} + +func TestAntigravityCompatEmptyStreamAfterKeepaliveIsCommittedNoContent(t *testing.T) { + err := runCompatStreamToEnd(t, 10*time.Millisecond, time.Second, 50*time.Millisecond) + require.Error(t, err) + require.True(t, IsAntigravityCompatCommittedNoContent(err), "got %v", err) +} + +func TestAntigravityCompatPreContentTimeoutAfterKeepaliveIsCommittedNoContent(t *testing.T) { + err := runCompatStreamToEnd(t, 10*time.Millisecond, 40*time.Millisecond, 200*time.Millisecond) + require.Error(t, err) + require.ErrorContains(t, err, "pre-content stream timeout") + require.True(t, IsAntigravityCompatCommittedNoContent(err), "got %v", err) +} + +func TestAntigravityCompatEmptyStreamBeforeKeepaliveStaysFailover(t *testing.T) { + err := runCompatStreamToEnd(t, time.Second, 2*time.Second, 10*time.Millisecond) + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "got %v", err) + require.False(t, IsAntigravityCompatCommittedNoContent(err)) +} + +func TestReleaseStickySessionAfterCommittedNoContent(t *testing.T) { + ctx := context.Background() + groupID := int64(10) + committed := &antigravityCompatCommittedNoContentError{msg: "empty Antigravity compatibility stream after keepalive"} + + t.Run("unbinds the session from the account that failed", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}} + svc := &GatewayService{cache: cache} + require.True(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, committed)) + _, bound := cache.sessionBindings["sess"] + require.False(t, bound) + }) + + t.Run("keeps a binding that already moved to another account", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 6}} + svc := &GatewayService{cache: cache} + require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, committed)) + require.Equal(t, int64(6), cache.sessionBindings["sess"]) + }) + + t.Run("ignores other errors", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}} + svc := &GatewayService{cache: cache} + require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, errors.New("stream data interval timeout"))) + require.Equal(t, int64(5), cache.sessionBindings["sess"]) + }) + + t.Run("no session hash is a no-op", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}} + svc := &GatewayService{cache: cache} + require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "", 5, committed)) + require.Equal(t, int64(5), cache.sessionBindings["sess"]) + }) +} From 5cbcb1b59104333a74520e4da6d57de8180358da Mon Sep 17 00:00:00 2001 From: William Drake Date: Sat, 14 Nov 2026 20:45:47 -0700 Subject: [PATCH 72/85] fix(antigravity): release the sticky account after a committed empty compat stream A compat stream (Responses / Chat Completions over Antigravity) sends a pre-content keepalive after 15 s, which commits HTTP 200. If the upstream then ends or times out with no content, the response can no longer fail over: the client gets an SSE empty_stream / stream_timeout error and retries. The session stayed bound to the same account, so every retry went back to it; on 2026-11-15 one Codex session at ~390k tokens hit empty_stream 22 times in 30 minutes on one account while the others served the same model. The stream now returns a typed committed-no-content error for both cases, and the Responses and Chat Completions handlers remove the session's sticky binding while it still points at the failed account. Only that session is affected: the account is not cooled or excluded for anyone else, so a request-caused empty stream cannot take a shared account offline. --- .../gateway_handler_chat_completions.go | 1 + .../handler/gateway_handler_responses.go | 3 ++ ...antigravity_compat_committed_no_content.go | 50 +++++++++++++++++++ .../antigravity_gateway_compat_stream.go | 6 +-- 4 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/antigravity_compat_committed_no_content.go diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 1db2e0584a..0ece6760d0 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -390,6 +390,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err) if result != nil { submitForwardUsage(result) } diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 79544a48de..47a652ec7c 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -373,6 +373,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + // The response is already committed, so the client retries; send that + // retry through scheduling again instead of back to this account. + h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err) if result != nil { submitForwardUsage(result) } diff --git a/backend/internal/service/antigravity_compat_committed_no_content.go b/backend/internal/service/antigravity_compat_committed_no_content.go new file mode 100644 index 0000000000..ed91c53db1 --- /dev/null +++ b/backend/internal/service/antigravity_compat_committed_no_content.go @@ -0,0 +1,50 @@ +package service + +import ( + "context" + "errors" + "log/slog" +) + +// antigravityCompatCommittedNoContentError reports a compat stream that +// committed HTTP 200 (pre-content keepalive) and then ended or timed out +// without any content. The response can no longer fail over, so the client +// retries; the handler releases the session's sticky account so that retry is +// scheduled afresh instead of returning to the account that just failed. +type antigravityCompatCommittedNoContentError struct { + msg string +} + +func newAntigravityCompatCommittedNoContentError(msg string) error { + return &antigravityCompatCommittedNoContentError{msg: msg} +} + +func (e *antigravityCompatCommittedNoContentError) Error() string { return e.msg } + +// IsAntigravityCompatCommittedNoContent reports whether err is a compat stream +// that committed its response and then produced no content. +func IsAntigravityCompatCommittedNoContent(err error) bool { + var target *antigravityCompatCommittedNoContentError + return errors.As(err, &target) +} + +// ReleaseStickySessionAfterCommittedNoContent removes the session's sticky +// binding when err is a committed no-content compat stream and the session is +// still bound to accountID. Only this session is affected: the account is not +// cooled or excluded for anyone else. Returns true when a binding was removed. +func (s *GatewayService) ReleaseStickySessionAfterCommittedNoContent(ctx context.Context, groupID *int64, sessionHash string, accountID int64, err error) bool { + if sessionHash == "" || accountID <= 0 || s.cache == nil || !IsAntigravityCompatCommittedNoContent(err) { + return false + } + gid := derefGroupID(groupID) + bound, getErr := s.cache.GetSessionAccountID(ctx, gid, sessionHash) + if getErr != nil || bound != accountID { + return false + } + if delErr := s.cache.DeleteSessionAccountID(ctx, gid, sessionHash); delErr != nil { + slog.Warn("antigravity_compat_sticky_release_failed", "group_id", gid, "account_id", accountID, "error", delErr) + return false + } + slog.Info("antigravity_compat_sticky_released", "group_id", gid, "account_id", accountID, "reason", err.Error()) + return true +} diff --git a/backend/internal/service/antigravity_gateway_compat_stream.go b/backend/internal/service/antigravity_gateway_compat_stream.go index 4dea4c453c..08e1ac14bb 100644 --- a/backend/internal/service/antigravity_gateway_compat_stream.go +++ b/backend/internal/service/antigravity_gateway_compat_stream.go @@ -171,7 +171,7 @@ func (s *antigravityCompatStreamSession) finish() (*antigravityStreamResult, err if !s.hasMeaningfulData() && !s.writer.Disconnected() { if s.preContentKeepaliveSent { s.adapter.WriteError(s.writer, "empty_stream") - return s.result(false), errors.New("empty Antigravity compatibility stream after keepalive") + return s.result(false), newAntigravityCompatCommittedNoContentError("empty Antigravity compatibility stream after keepalive") } return nil, antigravityCompatEmptyStreamError() } @@ -332,7 +332,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn preContentTimeout := func() (*antigravityStreamResult, error) { if session.preContentKeepaliveSent { writeAntigravityCompatStreamError(c, adapter, writer, "stream_timeout") - return session.collectResult(false), fmt.Errorf("pre-content stream timeout") + return session.collectResult(false), newAntigravityCompatCommittedNoContentError("pre-content stream timeout") } return nil, antigravityCompatEmptyStreamError() } @@ -393,7 +393,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn func handleAntigravityCompatEmptyStream(c *gin.Context, session *antigravityCompatStreamSession) (*antigravityStreamResult, error) { if session.preContentKeepaliveSent { writeAntigravityCompatStreamError(c, session.adapter, session.writer, "empty_stream") - return session.collectResult(false), errors.New("empty Antigravity compatibility stream after keepalive") + return session.collectResult(false), newAntigravityCompatCommittedNoContentError("empty Antigravity compatibility stream after keepalive") } return nil, antigravityCompatEmptyStreamError() } From b32ad6dfe113ed3e0ad64679d5c06adec6241961 Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 15 Oct 2026 18:58:36 +0800 Subject: [PATCH 73/85] =?UTF-8?q?feat(gemini):=20Vertex=20=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E6=94=AF=E6=8C=81=20us/eu=20=E5=A4=9A=E5=8C=BA?= =?UTF-8?q?=E5=9F=9F=E7=AB=AF=E7=82=B9=E5=B9=B6=E6=8C=89=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E9=99=8D=E7=BA=A7=20global?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 多区域使用 aiplatform.{us|eu}.rep.googleapis.com 主机,生成、Claude、显式缓存、 模型列表、批量生图的主机名统一由 vertexAPIHost 生成 - 内置模型可用区域表 vertexModelLocations:Gemini 账号区域为 us/eu 时,表内支持 该区域的模型走多区域端点,其余模型走 global;global、单区域账号与非 Gemini 平台账号不查表,vertex_model_locations 按模型覆盖仍优先 - 请求引用 Vertex 显式缓存时按缓存所在区域发送,账号区域变更后存量缓存仍可引用 - 多区域账号查询单个模型时核对 global 模型列表 --- .../internal/service/account_test_service.go | 2 +- .../service/batch_image_provider_vertex.go | 5 +- .../internal/service/gemini_cached_content.go | 25 ++-- .../gemini_chat_completions_compat_service.go | 2 +- .../service/gemini_messages_compat_service.go | 5 +- .../service/gemini_models_endpoints.go | 9 +- .../service/gemini_models_endpoints_test.go | 23 ++++ .../gemini_vertex_api_key_forward_test.go | 68 +++++++++ backend/internal/service/upstream_models.go | 5 +- backend/internal/service/vertex_locations.go | 58 ++++++++ .../internal/service/vertex_locations_test.go | 129 ++++++++++++++++++ .../service/vertex_service_account.go | 32 +++-- .../service/vertex_service_account_test.go | 4 +- 13 files changed, 331 insertions(+), 36 deletions(-) create mode 100644 backend/internal/service/vertex_locations.go create mode 100644 backend/internal/service/vertex_locations_test.go diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index fb1a40baf5..b195356fa9 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -2600,7 +2600,7 @@ func (s *AccountTestService) buildGeminiOAuthRequest(ctx context.Context, accoun } func (s *AccountTestService) buildGeminiServiceAccountRequest(ctx context.Context, account *Account, modelID string, payload []byte) (*http.Request, error) { - fullURL, err := buildVertexGeminiAccountURL(account, modelID, "streamGenerateContent", true) + fullURL, err := buildVertexGeminiAccountURL(account, modelID, "streamGenerateContent", true, "") if err != nil { return nil, err } diff --git a/backend/internal/service/batch_image_provider_vertex.go b/backend/internal/service/batch_image_provider_vertex.go index bb3363dfe3..a877c41ddd 100644 --- a/backend/internal/service/batch_image_provider_vertex.go +++ b/backend/internal/service/batch_image_provider_vertex.go @@ -569,10 +569,7 @@ func BuildVertexBatchPredictionJobsEndpoint(baseURL, projectID, location string) if strings.TrimSpace(baseURL) != "" { return strings.TrimRight(strings.TrimSpace(baseURL), "/") + "/v1/projects/" + url.PathEscape(projectID) + "/locations/" + url.PathEscape(location) + "/batchPredictionJobs", nil } - host := fmt.Sprintf("%s-aiplatform.googleapis.com", location) - if location == "global" { - host = "aiplatform.googleapis.com" - } + host := vertexAPIHost(location) return fmt.Sprintf("https://%s/v1/projects/%s/locations/%s/batchPredictionJobs", host, url.PathEscape(projectID), url.PathEscape(location)), nil } diff --git a/backend/internal/service/gemini_cached_content.go b/backend/internal/service/gemini_cached_content.go index 95264148d0..2295a80efe 100644 --- a/backend/internal/service/gemini_cached_content.go +++ b/backend/internal/service/gemini_cached_content.go @@ -331,6 +331,20 @@ func FindGeminiCachedContentReference(body []byte) (*GeminiCachedContentReferenc return ref, nil } +// geminiCachedContentLocationInBody 返回请求体引用的 Vertex 显式缓存所在区域;未引用 Vertex 缓存时返回空串。 +func geminiCachedContentLocationInBody(body []byte) string { + if !bytes.Contains(body, []byte("/cachedContents/")) { + return "" + } + for _, path := range geminiCachedContentReferencePaths { + name := strings.TrimSpace(gjson.GetBytes(body, path).String()) + if m := geminiCachedContentVertexName.FindStringSubmatch(name); m != nil { + return m[1] + } + } + return "" +} + // checkGeminiCachedContentReferenceKeys 拒绝对象中重复出现的 uniqueKeys 与 snake_case 写法的缓存引用键。 func checkGeminiCachedContentReferenceKeys(obj gjson.Result, uniqueKeys ...string) error { seen := make(map[string]bool, len(uniqueKeys)) @@ -1151,7 +1165,7 @@ func geminiCachedContentCollectionURL(account *Account, base, mappedModel string return "", fmt.Errorf("invalid vertex location: %s", location) } return fmt.Sprintf("https://%s/v1/projects/%s/locations/%s/cachedContents", - geminiCachedContentVertexHost(location), url.PathEscape(projectID), url.PathEscape(location)), nil + vertexAPIHost(location), url.PathEscape(projectID), url.PathEscape(location)), nil default: return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type) } @@ -1173,19 +1187,12 @@ func geminiCachedContentResourceURL(account *Account, base, upstreamName string) if m == nil { return "", fmt.Errorf("invalid upstream cached content name: %s", upstreamName) } - return fmt.Sprintf("https://%s/v1/%s", geminiCachedContentVertexHost(m[1]), upstreamName), nil + return fmt.Sprintf("https://%s/v1/%s", vertexAPIHost(m[1]), upstreamName), nil default: return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type) } } -func geminiCachedContentVertexHost(location string) string { - if location == "global" { - return "aiplatform.googleapis.com" - } - return location + "-aiplatform.googleapis.com" -} - // GeminiCachedContentView 返回客户端可见的缓存元数据。 func GeminiCachedContentView(record *GeminiCachedContent) map[string]any { view := map[string]any{ diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index f0716e003c..d40b8a6e85 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -430,7 +430,7 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF if clientStream { action = "streamGenerateContent" } - fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, clientStream) + fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, clientStream, "") if err != nil { return nil, "", err } diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 9d2ad1ae45..861a08ad12 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -692,7 +692,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex if req.Stream { action = "streamGenerateContent" } - fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, req.Stream) + fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, req.Stream, "") if err != nil { return nil, "", err } @@ -1247,8 +1247,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. requestIDHeader = "x-request-id" case AccountTypeServiceAccount: + cachedContentLocation := geminiCachedContentLocationInBody(body) buildReq = func(ctx context.Context) (*http.Request, string, error) { - fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, upstreamAction, useUpstreamStream) + fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, upstreamAction, useUpstreamStream, cachedContentLocation) if err != nil { return nil, "", err } diff --git a/backend/internal/service/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go index 34a86444d1..f7a311d6a0 100644 --- a/backend/internal/service/gemini_models_endpoints.go +++ b/backend/internal/service/gemini_models_endpoints.go @@ -188,7 +188,8 @@ func (s *GeminiMessagesCompatService) ForwardListModels(ctx context.Context, acc } // ForwardGetModel 读取账号上游的单个模型信息,返回 AI Studio 格式的响应(GET /v1beta/models/{model})。 -// Vertex 服务账号在该模型生成请求所用区域的模型列表中查找,找不到时返回 404;Vertex API Key 账号返回内置信息。 +// Vertex 服务账号在该模型生成请求所用区域的模型列表中查找,找不到时返回 404;该区域为多区域(us/eu)时 +// 查 global 列表,多区域可用性以 vertexModelLocations 为准。Vertex API Key 账号返回内置信息。 func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, account *Account, model string) (*UpstreamHTTPResult, error) { if account == nil { return nil, errors.New("account is nil") @@ -200,7 +201,11 @@ func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, accou return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model)) } - modelIDs, failure, err := s.listVertexGeminiModels(ctx, account, account.VertexLocation(model)) + location := account.VertexLocation(model) + if isVertexMultiRegion(location) { + location = vertexGlobalLocation + } + modelIDs, failure, err := s.listVertexGeminiModels(ctx, account, location) if err != nil { return nil, err } diff --git a/backend/internal/service/gemini_models_endpoints_test.go b/backend/internal/service/gemini_models_endpoints_test.go index e33b85d809..962f642779 100644 --- a/backend/internal/service/gemini_models_endpoints_test.go +++ b/backend/internal/service/gemini_models_endpoints_test.go @@ -206,3 +206,26 @@ func TestForwardListModels_ResponseOverReadLimitFails(t *testing.T) { _, err := svc.ForwardListModels(context.Background(), account) require.ErrorContains(t, err, "exceeds 16 bytes") } + +// Scenario: 多区域账号查单个模型与列模型都读 global 发布方列表。 +func TestForwardModels_VertexMultiRegionAccountReadsGlobalList(t *testing.T) { + account := vertexModelSyncTestAccount(map[string]any{"location": "us"}) + listBody := `{"publisherModels":[{"name":"publishers/google/models/gemini-3.6-flash"},{"name":"publishers/google/models/gemini-3.1-pro-preview"}]}` + const globalList = "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300" + + for _, model := range []string{"gemini-3.6-flash", "gemini-3.1-pro-preview"} { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, listBody)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + res, err := svc.ForwardGetModel(context.Background(), account, model) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode, model) + require.Equal(t, globalList, upstream.lastReq.URL.String()) + } + + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, listBody)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + res, err := svc.ForwardListModels(context.Background(), account) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, globalList, upstream.lastReq.URL.String()) +} diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go index 1b57bbb1fc..f405a3a065 100644 --- a/backend/internal/service/gemini_vertex_api_key_forward_test.go +++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go @@ -163,3 +163,71 @@ func TestGeminiForwardNative_VertexSharedCapacity429RetriesSameAccountWithoutCoo }) } } + +// Scenario: 多区域账号按模型支持的区域发送,不支持的模型走 global;引用显式缓存时按缓存所在区域发送; +// 无 project_id 的 API Key 账号始终走 Express 全局端点。 +func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedContent(t *testing.T) { + gin.SetMode(gin.TestMode) + const contents = `"contents":[{"role":"user","parts":[{"text":"hi"}]}]` + cases := []struct { + name string + projectID string + location string + model string + body string + want string + }{ + { + name: "supported model uses multi-region endpoint", + projectID: "my-project", + location: "us", + model: "gemini-3.7-flash", + body: `{` + contents + `}`, + want: "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent", + }, + { + name: "unsupported model falls back to global", + projectID: "my-project", + location: "us", + model: "gemini-3.1-pro-preview", + body: `{` + contents + `}`, + want: "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3.1-pro-preview:generateContent", + }, + { + name: "global cached content on multi-region account stays on global", + projectID: "my-project", + location: "us", + model: "gemini-3.7-flash", + body: `{"cachedContent":"projects/my-project/locations/global/cachedContents/42",` + contents + `}`, + want: "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3.7-flash:generateContent", + }, + { + name: "multi-region cached content on global account uses its region", + projectID: "my-project", + location: "global", + model: "gemini-3.7-flash", + body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, + want: "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent", + }, + { + name: "express mode ignores cached content region", + location: "us", + model: "gemini-3.7-flash", + body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, + want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.7-flash:generateContent", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, _ := newGeminiNativeTestContext(t) + account := geminiVertexAPIKeyTestAccount(tc.projectID) + account.Credentials["location"] = tc.location + + _, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, []byte(tc.body)) + require.NoError(t, err) + require.Equal(t, 1, httpStub.calls) + require.Equal(t, tc.want, httpStub.lastReq.URL.String()) + }) + } +} diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 3d04d8ccb2..c6587cee50 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -1434,10 +1434,7 @@ func buildVertexPublisherModelsURL(location, pageToken string) (string, error) { if !vertexLocationPattern.MatchString(location) { return "", fmt.Errorf("invalid vertex location: %s", location) } - host := location + "-aiplatform.googleapis.com" - if location == "global" { - host = vertexGlobalHost - } + host := vertexAPIHost(location) query := url.Values{"pageSize": []string{strconv.Itoa(vertexPublisherModelsPageSize)}} if pageToken != "" { query.Set("pageToken", pageToken) diff --git a/backend/internal/service/vertex_locations.go b/backend/internal/service/vertex_locations.go new file mode 100644 index 0000000000..efc8fa1162 --- /dev/null +++ b/backend/internal/service/vertex_locations.go @@ -0,0 +1,58 @@ +package service + +import ( + "slices" + "strings" +) + +const ( + vertexGlobalLocation = "global" + vertexLocationUS = "us" + vertexLocationEU = "eu" +) + +// vertexModelLocations 列出 Vertex Gemini 模型可用的区域。Gemini 账号区域配置为多区域(us/eu)时, +// 表内声明支持该多区域的模型走对应多区域端点,其余模型(含未列出的模型)走 global。 +// 账号区域为 global 或单区域时、以及非 Gemini 平台账号不查此表。 +var vertexModelLocations = map[string][]string{ + "gemini-3.1-flash-image": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-3.1-flash-lite": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-3.5-flash": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-3.5-flash-lite": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-3.6-flash": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-3.7-flash": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-3.8-flash": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, + "gemini-4-argon": {vertexGlobalLocation, vertexLocationUS, vertexLocationEU}, +} + +// isVertexMultiRegion 判断区域是否为 Vertex 多区域(us/eu)。 +func isVertexMultiRegion(location string) bool { + return location == vertexLocationUS || location == vertexLocationEU +} + +// vertexAPIHost 返回区域对应的 Vertex AI API 主机:global 用全局主机,多区域用 aiplatform.{loc}.rep 主机, +// 单区域用 {loc}-aiplatform 主机。 +func vertexAPIHost(location string) string { + switch { + case location == vertexGlobalLocation: + return vertexGlobalHost + case isVertexMultiRegion(location): + return "aiplatform." + location + ".rep.googleapis.com" + default: + return location + "-aiplatform.googleapis.com" + } +} + +// resolveVertexModelLocation 返回模型在账号区域下实际使用的区域:账号为多区域而模型不支持该多区域时用 global。 +func resolveVertexModelLocation(accountLocation, model string) string { + if !isVertexMultiRegion(accountLocation) { + return accountLocation + } + if i := strings.LastIndex(model, "/"); i >= 0 { + model = model[i+1:] + } + if slices.Contains(vertexModelLocations[strings.TrimSpace(model)], accountLocation) { + return accountLocation + } + return vertexGlobalLocation +} diff --git a/backend/internal/service/vertex_locations_test.go b/backend/internal/service/vertex_locations_test.go new file mode 100644 index 0000000000..36aa37d308 --- /dev/null +++ b/backend/internal/service/vertex_locations_test.go @@ -0,0 +1,129 @@ +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestVertexAPIHost(t *testing.T) { + require.Equal(t, "aiplatform.googleapis.com", vertexAPIHost("global")) + require.Equal(t, "aiplatform.us.rep.googleapis.com", vertexAPIHost("us")) + require.Equal(t, "aiplatform.eu.rep.googleapis.com", vertexAPIHost("eu")) + require.Equal(t, "us-central1-aiplatform.googleapis.com", vertexAPIHost("us-central1")) +} + +func TestAccountVertexLocationResolvesMultiRegionPerModel(t *testing.T) { + account := func(creds map[string]any) *Account { + return &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: creds} + } + us := account(map[string]any{"location": "us"}) + require.Equal(t, "us", us.VertexLocation("gemini-3.7-flash")) + require.Equal(t, "us", us.VertexLocation("publishers/google/models/gemini-3.8-flash")) + require.Equal(t, "global", us.VertexLocation("gemini-3.1-pro-preview")) + require.Equal(t, "global", us.VertexLocation("gemini-2.5-flash")) + require.Equal(t, "global", us.VertexLocation("")) + + eu := account(map[string]any{"vertex_location": "eu"}) + require.Equal(t, "eu", eu.VertexLocation("gemini-3.1-flash-lite")) + require.Equal(t, "global", eu.VertexLocation("gemini-3-pro-image")) + + regional := account(map[string]any{"location": "us-central1"}) + require.Equal(t, "us-central1", regional.VertexLocation("gemini-3.1-pro-preview")) + require.Equal(t, "us-central1", regional.VertexLocation("")) + + global := account(map[string]any{"location": "global"}) + require.Equal(t, "global", global.VertexLocation("gemini-3.7-flash")) + + override := account(map[string]any{"location": "us", "vertex_model_locations": map[string]any{"gemini-3.7-flash": "global", "gemini-2.5-flash": "us"}}) + require.Equal(t, "global", override.VertexLocation("gemini-3.7-flash")) + require.Equal(t, "us", override.VertexLocation("gemini-2.5-flash")) + require.Equal(t, "us", override.VertexLocation("gemini-3.8-flash")) + + require.Equal(t, vertexDefaultLocation, account(nil).VertexLocation("gemini-3.7-flash")) + + anthropic := &Account{Platform: PlatformAnthropic, Type: AccountTypeServiceAccount, Credentials: map[string]any{"location": "us"}} + require.Equal(t, "us", anthropic.VertexLocation("claude-sonnet-4-5@20250929")) +} + +func TestBuildVertexGeminiAccountURLMultiRegion(t *testing.T) { + account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"project_id": "p1", "location": "us"}} + + got, err := buildVertexGeminiAccountURL(account, "gemini-3.7-flash", "streamGenerateContent", true, "") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/p1/locations/us/publishers/google/models/gemini-3.7-flash:streamGenerateContent?alt=sse", got) + + got, err = buildVertexGeminiAccountURL(account, "gemini-3.1-pro-preview", "generateContent", false, "") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/p1/locations/global/publishers/google/models/gemini-3.1-pro-preview:generateContent", got) + + got, err = buildVertexGeminiAccountURL(account, "gemini-3.7-flash", "generateContent", false, "global") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/p1/locations/global/publishers/google/models/gemini-3.7-flash:generateContent", got) + + global := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"project_id": "p1", "location": "global"}} + got, err = buildVertexGeminiAccountURL(global, "gemini-3.7-flash", "countTokens", false, "us") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/p1/locations/us/publishers/google/models/gemini-3.7-flash:countTokens", got) +} + +func TestBuildVertexAnthropicURLMultiRegionHost(t *testing.T) { + got, err := buildVertexAnthropicURL("my-project", "us", "claude-sonnet-4-5@20250929", true) + require.NoError(t, err) + require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/anthropic/models/claude-sonnet-4-5@20250929:streamRawPredict", got) +} + +func TestGeminiCachedContentLocationInBody(t *testing.T) { + cases := map[string]string{ + `{"cachedContent":"projects/123/locations/us/cachedContents/456","contents":[]}`: "us", + `{"contents":[],"cachedContent":"projects/p-1/locations/global/cachedContents/456"}`: "global", + `{"generateContentRequest":{"cachedContent":"projects/123/locations/eu/cachedContents/9"}}`: "eu", + `{"cachedContent":"cachedContents/abc","contents":[]}`: "", + `{"contents":[{"role":"user","parts":[{"text":"projects/1/locations/us/cachedContents/2"}]}]}`: "", + `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`: "", + `{"cachedContent":"projects/123/locations/us/cachedContents/../x","contents":[]}`: "", + } + for body, want := range cases { + require.Equal(t, want, geminiCachedContentLocationInBody([]byte(body)), body) + } +} + +func TestGeminiCachedContentVertexURLsMultiRegion(t *testing.T) { + account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"project_id": "proj-1", "location": "us"}} + + model, err := GeminiCachedContentUpstreamModelResource(account, "gemini-3.7-flash") + require.NoError(t, err) + require.Equal(t, "projects/proj-1/locations/us/publishers/google/models/gemini-3.7-flash", model) + + collection, err := geminiCachedContentCollectionURL(account, "", "gemini-3.7-flash") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/proj-1/locations/us/cachedContents", collection) + + model, err = GeminiCachedContentUpstreamModelResource(account, "gemini-3.1-pro-preview") + require.NoError(t, err) + require.Equal(t, "projects/proj-1/locations/global/publishers/google/models/gemini-3.1-pro-preview", model) + + collection, err = geminiCachedContentCollectionURL(account, "", "gemini-3.1-pro-preview") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/proj-1/locations/global/cachedContents", collection) + + resource, err := geminiCachedContentResourceURL(account, "", "projects/123/locations/us/cachedContents/456") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/123/locations/us/cachedContents/456", resource) + + resource, err = geminiCachedContentResourceURL(account, "", "projects/123/locations/global/cachedContents/456") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/123/locations/global/cachedContents/456", resource) +} + +func TestBuildVertexPublisherModelsURLMultiRegionHost(t *testing.T) { + u, err := buildVertexPublisherModelsURL("eu", "") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.eu.rep.googleapis.com/v1beta1/publishers/google/models?pageSize=300", u) +} + +func TestBuildVertexBatchPredictionJobsEndpointMultiRegionHost(t *testing.T) { + got, err := BuildVertexBatchPredictionJobsEndpoint("", "my-project", "us") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/batchPredictionJobs", got) +} diff --git a/backend/internal/service/vertex_service_account.go b/backend/internal/service/vertex_service_account.go index fdc7d41e48..6486791cf2 100644 --- a/backend/internal/service/vertex_service_account.go +++ b/backend/internal/service/vertex_service_account.go @@ -84,6 +84,8 @@ func (a *Account) VertexProjectID() string { return "" } +// VertexLocation 返回模型请求使用的区域:vertex_model_locations 显式指定优先;否则取账号区域, +// Gemini 账号区域为多区域(us/eu)时按 vertexModelLocations 判断模型是否支持,不支持的走 global。 func (a *Account) VertexLocation(model string) string { if a == nil { return vertexDefaultLocation @@ -95,6 +97,15 @@ func (a *Account) VertexLocation(model string) string { } } } + location := a.vertexAccountLocation() + if a.Platform != PlatformGemini { + return location + } + return resolveVertexModelLocation(location, model) +} + +// vertexAccountLocation 返回账号配置的区域,未配置时为 vertexDefaultLocation。 +func (a *Account) vertexAccountLocation() string { if v := strings.TrimSpace(a.GetCredential("location")); v != "" { return v } @@ -328,12 +339,17 @@ func vertexServiceAccountNotFoundError(err error) (*vertexTokenRequestError, boo } // buildVertexGeminiAccountURL 按账号构造 Vertex Gemini 请求地址:未配置 project_id 的 API Key 账号 -// 走 Express mode 全局端点,其余账号走项目级端点。 -func buildVertexGeminiAccountURL(account *Account, model, action string, stream bool) (string, error) { +// 走 Express mode 全局端点,其余账号走项目级端点。cachedContentLocation 是请求引用的显式缓存所在区域, +// 非空时按该区域发送(缓存只能在其所在区域的端点上引用),为空时按 VertexLocation 选区域。 +func buildVertexGeminiAccountURL(account *Account, model, action string, stream bool, cachedContentLocation string) (string, error) { if account.IsVertexAPIKey() && account.VertexProjectID() == "" { return buildVertexGeminiExpressURL(model, action, stream) } - return buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(model), model, action, stream) + location := cachedContentLocation + if location == "" { + location = account.VertexLocation(model) + } + return buildVertexGeminiURL(account.VertexProjectID(), location, model, action, stream) } // buildVertexGeminiExpressURL 构造不带项目与区域的全局端点地址,仅 API Key 认证可用。 @@ -404,10 +420,7 @@ func buildVertexGeminiURL(projectID, location, model, action string, stream bool if err := validateVertexGeminiAction(action); err != nil { return "", err } - host := fmt.Sprintf("%s-aiplatform.googleapis.com", location) - if location == "global" { - host = vertexGlobalHost - } + host := vertexAPIHost(location) u := fmt.Sprintf( "https://%s/v1/projects/%s/locations/%s/publishers/google/models/%s:%s", host, @@ -442,10 +455,7 @@ func buildVertexAnthropicURL(projectID, location, model string, stream bool) (st if stream { action = "streamRawPredict" } - host := fmt.Sprintf("%s-aiplatform.googleapis.com", location) - if location == "global" { - host = "aiplatform.googleapis.com" - } + host := vertexAPIHost(location) escapedModel := strings.ReplaceAll(url.PathEscape(model), "%40", "@") return fmt.Sprintf( "https://%s/v1/projects/%s/locations/%s/publishers/anthropic/models/%s:%s", diff --git a/backend/internal/service/vertex_service_account_test.go b/backend/internal/service/vertex_service_account_test.go index 77cb6617c7..f8cf6e7975 100644 --- a/backend/internal/service/vertex_service_account_test.go +++ b/backend/internal/service/vertex_service_account_test.go @@ -63,14 +63,14 @@ func TestBuildVertexGeminiAccountURL(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: tc.credentials} - got, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "streamGenerateContent", true) + got, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "streamGenerateContent", true, "") require.NoError(t, err) require.Equal(t, tc.want, got) }) } account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "k"}} - _, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "rawPredict", false) + _, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "rawPredict", false, "") require.ErrorContains(t, err, "unsupported vertex gemini action") } From 68071ddde1ee4de8fb31b82536568cd831fde7be Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 15 Oct 2026 19:33:48 +0800 Subject: [PATCH 74/85] =?UTF-8?q?feat(gemini):=20Vertex=20=E5=A4=9A?= =?UTF-8?q?=E5=8C=BA=E5=9F=9F=E7=AB=AF=E7=82=B9=E6=8C=89=E5=AE=9E=E9=99=85?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E5=8C=BA=E5=9F=9F=E5=8A=A0=E4=BB=B7=2010%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 转发结果记录上游端点价格倍数:Gemini 请求实际发往 us/eu 且模型在 vertexModelLocations 中声明支持该多区域时为 1.1,发往 global 时为 1; 引用显式缓存的请求按缓存所在区域判断 - 倍数只作用于按 token 计费的费用(输入、输出、缓存读取、缓存创建), 按次与按张计费不变,显式缓存存储费与联网搜索费在其后按原价叠加 - 建缓存的预扣报价与记账按缓存所在区域带上倍数 - 账号统计成本按模型定价文件计算时同样乘倍数,自定义规则与渠道计费档不变 --- .../handler/gemini_cached_contents_handler.go | 13 ++-- .../internal/service/account_stats_pricing.go | 11 +++- .../service/account_stats_pricing_test.go | 48 ++++++++++----- backend/internal/service/gateway_service.go | 11 ++++ .../internal/service/gateway_usage_billing.go | 15 ++++- .../service/gemini_cached_content_test.go | 60 +++++++++++++++++++ .../gemini_chat_completions_compat_service.go | 2 + .../service/gemini_messages_compat_service.go | 6 +- .../gemini_vertex_api_key_forward_test.go | 48 +++++++++++++-- .../internal/service/openai_gateway_usage.go | 2 +- backend/internal/service/vertex_locations.go | 47 ++++++++++++--- .../internal/service/vertex_locations_test.go | 30 ++++++++++ .../service/vertex_service_account.go | 5 +- 13 files changed, 255 insertions(+), 43 deletions(-) diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index e160f8cef9..3f14e37042 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -275,6 +275,7 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) { Result: &service.ForwardResult{ Model: modelName, UpstreamModel: mappedModel, Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours, + UpstreamPriceMultiplier: service.VertexUpstreamPriceMultiplier(account, mappedModel, ""), }, APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields, }) @@ -674,15 +675,17 @@ func (h *GatewayHandler) submitGeminiCachedContentUsage( if inputTokens <= 0 && storageTokenHours <= 0 { return } + priceMultiplier := service.VertexUpstreamPriceMultiplier(account, upstreamModel, "") if upstreamModel == model { upstreamModel = "" } result := &service.ForwardResult{ - RequestID: requestID, - Model: model, - UpstreamModel: upstreamModel, - Usage: service.ClaudeUsage{InputTokens: inputTokens}, - CacheStorageTokenHours: storageTokenHours, + RequestID: requestID, + Model: model, + UpstreamModel: upstreamModel, + Usage: service.ClaudeUsage{InputTokens: inputTokens}, + CacheStorageTokenHours: storageTokenHours, + UpstreamPriceMultiplier: priceMultiplier, } inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) diff --git a/backend/internal/service/account_stats_pricing.go b/backend/internal/service/account_stats_pricing.go index 5cf8971d54..4bb1d7f5d4 100644 --- a/backend/internal/service/account_stats_pricing.go +++ b/backend/internal/service/account_stats_pricing.go @@ -21,6 +21,7 @@ import ( // pricingAt 与本次客户计费使用同一时刻,避免跨峰谷请求的成本与售价错位。 // longContextPricingEnabled 表示上游是否对本次请求收取长上下文费率,用于优先级 3; // 由 accountStatsLongContextPricingEnabled 按账号开关得出,不受分组售价开关影响。 +// upstreamPriceFactor 是上游按实际请求端点计价的倍数(见 ForwardResult.UpstreamPriceMultiplier),用于优先级 3。 // reasoningEffort 是最终转发等级;按账号统计定价中配置的等级倍率计费。 func resolveAccountStatsCost( ctx context.Context, @@ -35,6 +36,7 @@ func resolveAccountStatsCost( serviceTier string, pricingAt time.Time, longContextPricingEnabled bool, + upstreamPriceFactor float64, reasoningEfforts ...string, ) *float64 { reasoningEffort := "" @@ -67,7 +69,11 @@ func resolveAccountStatsCost( // 优先级 3:模型定价文件(LiteLLM)默认价格 if billingService != nil { - return tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, pricingAt, longContextPricingEnabled, reasoningEffort) + cost := tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, pricingAt, longContextPricingEnabled, reasoningEffort) + if cost != nil && upstreamPriceFactor > 0 { + *cost *= upstreamPriceFactor + } + return cost } return nil @@ -277,6 +283,7 @@ func applyAccountStatsCost( totalCost float64, pricingAt time.Time, longContextPricingEnabled bool, + upstreamPriceFactor float64, ) { model := upstreamModel if model == "" { @@ -295,7 +302,7 @@ func applyAccountStatsCost( reasoningEffort = *usageLog.ReasoningEffort } usageLog.AccountStatsCost = resolveAccountStatsCost( - ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, pricingAt, longContextPricingEnabled, reasoningEffort, + ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, pricingAt, longContextPricingEnabled, upstreamPriceFactor, reasoningEffort, ) } diff --git a/backend/internal/service/account_stats_pricing_test.go b/backend/internal/service/account_stats_pricing_test.go index 0f5d236ca1..1c21d32ae2 100644 --- a/backend/internal/service/account_stats_pricing_test.go +++ b/backend/internal/service/account_stats_pricing_test.go @@ -738,7 +738,7 @@ func TestResolveAccountStatsCost_DeepSeekPricingPriority(t *testing.T) { groupID = 99 } cost := resolveAccountStatsCost(context.Background(), cs, newTestBillingService(), - 1, groupID, "deepseek-v4-flash", UsageTokens{InputTokens: 1000}, 1, 0.75, "", peak, true) + 1, groupID, "deepseek-v4-flash", UsageTokens{InputTokens: 1000}, 1, 0.75, "", peak, true, 1) if tt.noChannel { require.Nil(t, cost) return @@ -759,7 +759,7 @@ func TestResolveAccountStatsCost_NilChannelService(t *testing.T) { nil, // channelService is nil newTestBillingServiceWithPrices(map[string]*ModelPricing{}), 1, 1, "claude-sonnet-4", - UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -775,7 +775,7 @@ func TestResolveAccountStatsCost_EmptyUpstreamModel(t *testing.T) { cs, newTestBillingServiceWithPrices(map[string]*ModelPricing{}), 1, 1, "", // empty upstream model - UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -792,7 +792,7 @@ func TestResolveAccountStatsCost_GetChannelForGroupReturnsNil(t *testing.T) { cs, newTestBillingServiceWithPrices(map[string]*ModelPricing{}), 1, 99, "claude-sonnet-4", // groupID 99 has no channel - UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -823,7 +823,7 @@ func TestResolveAccountStatsCost_HitsCustomRule(t *testing.T) { context.Background(), cs, nil, // billingService not needed when custom rule hits 1, 10, "claude-sonnet-4", - tokens, 1, 999.0, "priority", time.Time{}, true, // 自定义账号价格不叠加服务层级倍率 + tokens, 1, 999.0, "priority", time.Time{}, true, 1, // 自定义账号价格不叠加服务层级倍率 ) require.NotNil(t, result) // 100*0.01 + 50*0.02 = 1.0 + 1.0 = 2.0 @@ -845,7 +845,7 @@ func TestResolveAccountStatsCost_ApplyPricingToAccountStats_UsesTotalCost(t *tes context.Background(), cs, nil, 1, 10, "claude-sonnet-4", - tokens, 1, 0.75, "priority", time.Time{}, true, // 已完成用户计费,不再重复应用服务层级倍率 + tokens, 1, 0.75, "priority", time.Time{}, true, 1, // 已完成用户计费,不再重复应用服务层级倍率 ) require.NotNil(t, result) require.InDelta(t, 0.75, *result, 1e-12) @@ -863,7 +863,7 @@ func TestResolveAccountStatsCost_ApplyPricingToAccountStats_ZeroTotalCost_Return context.Background(), cs, nil, 1, 10, "claude-sonnet-4", - UsageTokens{}, 1, 0.0, "", time.Time{}, true, // totalCost = 0 + UsageTokens{}, 1, 0.0, "", time.Time{}, true, 1, // totalCost = 0 ) require.Nil(t, result) } @@ -890,13 +890,31 @@ func TestResolveAccountStatsCost_FallsBackToLiteLLM(t *testing.T) { context.Background(), cs, bs, 1, 10, "claude-sonnet-4", - tokens, 1, 999.0, "", time.Time{}, true, // totalCost ignored + tokens, 1, 999.0, "", time.Time{}, true, 1, // totalCost ignored ) require.NotNil(t, result) // 100*0.001 + 50*0.002 = 0.1 + 0.1 = 0.2 require.InDelta(t, 0.2, *result, 1e-12) } +// Scenario: 上游端点价格倍数只放大模型定价文件档,渠道计费档保持原值。 +func TestResolveAccountStatsCost_UpstreamPriceFactorScalesModelFilePricingOnly(t *testing.T) { + bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{ + "claude-sonnet-4": {InputPricePerToken: 0.001, OutputPricePerToken: 0.002}, + }) + tokens := UsageTokens{InputTokens: 100, OutputTokens: 50} + + modelFile := newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, 10, "anthropic") + result := resolveAccountStatsCost(context.Background(), modelFile, bs, 1, 10, "claude-sonnet-4", tokens, 1, 999.0, "", time.Time{}, true, 1.1) + require.NotNil(t, result) + require.InDelta(t, 0.22, *result, 1e-12) + + applyPricing := newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive, ApplyPricingToAccountStats: true}, 10, "anthropic") + result = resolveAccountStatsCost(context.Background(), applyPricing, bs, 1, 10, "claude-sonnet-4", tokens, 1, 0.75, "", time.Time{}, true, 1.1) + require.NotNil(t, result) + require.InDelta(t, 0.75, *result, 1e-12) +} + func TestResolveAccountStatsCost_FallbackHonorsAnthropicFast(t *testing.T) { channel := &Channel{ID: 1, Status: StatusActive} cs := newTestChannelServiceForStats(t, channel, 10, "anthropic") @@ -911,7 +929,7 @@ func TestResolveAccountStatsCost_FallbackHonorsAnthropicFast(t *testing.T) { context.Background(), cs, bs, 1, 10, "claude-opus-5", UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000}, - 1, 0, "fast", time.Time{}, true, + 1, 0, "fast", time.Time{}, true, 1, ) require.NotNil(t, result) require.InDelta(t, 60, *result, 1e-12) @@ -930,7 +948,7 @@ func TestResolveAccountStatsCost_Gemini36FlashTierUsesFallbackPricing(t *testing context.Background(), cs, bs, 1, 10, "gemini-3.6-flash-low", - UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{}, true, + UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{}, true, 1, ) require.NotNil(t, result) require.InDelta(t, 4.575, *result, 1e-12) @@ -954,7 +972,7 @@ func TestResolveAccountStatsCost_AllMiss_ReturnsNil(t *testing.T) { context.Background(), cs, bs, 1, 10, "totally-unknown-model", - tokens, 1, 0.0, "", time.Time{}, true, + tokens, 1, 0.0, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -971,7 +989,7 @@ func TestResolveAccountStatsCost_NilBillingService_SkipsLiteLLM(t *testing.T) { context.Background(), cs, nil, // billingService is nil 1, 10, "claude-sonnet-4", - UsageTokens{InputTokens: 100}, 1, 0.0, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.0, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -1004,7 +1022,7 @@ func TestResolveAccountStatsCost_CustomRulePriorityOverApplyPricing(t *testing.T context.Background(), cs, nil, 1, 10, "claude-sonnet-4", - tokens, 1, 99.0, "", time.Time{}, true, // totalCost = 99.0 (would be used if ApplyPricing wins) + tokens, 1, 99.0, "", time.Time{}, true, 1, // totalCost = 99.0 (would be used if ApplyPricing wins) ) require.NotNil(t, result) // Custom rule: 100*0.05 = 5.0 (NOT 99.0 from totalCost) @@ -1032,7 +1050,7 @@ func TestApplyAccountStatsCost_UsesUsageLogServiceTier(t *testing.T) { applyAccountStatsCost( context.Background(), usageLog, cs, bs, 1, 10, "gpt-5.6-sol", "gpt-5.6-sol", - UsageTokens{InputTokens: 100, OutputTokens: 50}, 999, time.Time{}, true, + UsageTokens{InputTokens: 100, OutputTokens: 50}, 999, time.Time{}, true, 1, ) require.NotNil(t, usageLog.AccountStatsCost) @@ -1081,7 +1099,7 @@ func TestApplyAccountStatsCost_LongContextFollowsAccountGate(t *testing.T) { usageLog := &UsageLog{ServiceTier: &tt.tier} applyAccountStatsCost(context.Background(), usageLog, cs, bs, 1, 10, "gpt-5.6-sol", "gpt-5.6-sol", tokens, 999, time.Time{}, - accountStatsLongContextPricingEnabled(tt.gate)) + accountStatsLongContextPricingEnabled(tt.gate), 1) require.NotNil(t, usageLog.AccountStatsCost) require.InDelta(t, tt.wantCost, *usageLog.AccountStatsCost, 1e-12) }) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..5481579351 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -658,6 +658,17 @@ type ForwardResult struct { // CacheStorageTokenHours 显式上下文缓存的存储量(缓存 token 数 × 存储小时数),按计费模型的 // 存储单价折算为费用后叠加在 token 费用之上。 CacheStorageTokenHours float64 + // UpstreamPriceMultiplier 是上游按实际请求端点计价相对计费模型价格的倍数(见 VertexUpstreamPriceMultiplier), + // 只作用于 token 费用;0 按 1 处理。 + UpstreamPriceMultiplier float64 +} + +// upstreamPriceFactor 返回 UpstreamPriceMultiplier,未设置时为 1。 +func (r *ForwardResult) upstreamPriceFactor() float64 { + if r == nil || r.UpstreamPriceMultiplier <= 0 { + return 1 + } + return r.UpstreamPriceMultiplier } // GatewayFailureStage identifies which request stage failed. The zero value is diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 10e0992c9c..4522e5e958 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -857,7 +857,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage ImageOutputTokens: result.Usage.ImageOutputTokens, }, cost.TotalCost-cacheStorageCost, pricingAt, - accountStatsLongContextPricingEnabled(nil), + accountStatsLongContextPricingEnabled(nil), result.upstreamPriceFactor(), ) addCacheStorageToAccountStatsCost(usageLog, cacheStorageCost) } @@ -1011,6 +1011,14 @@ func addCacheStorageToAccountStatsCost(usageLog *UsageLog, storageCost float64) usageLog.AccountStatsCost = &cost } +// applyUpstreamPriceFactor 把上游端点价格倍数作用于按 token 计费的费用,按次等其他计费模式不受影响。 +func applyUpstreamPriceFactor(cost *CostBreakdown, result *ForwardResult) { + if cost == nil || (cost.BillingMode != "" && cost.BillingMode != string(BillingModeToken)) { + return + } + applyCostBreakdownMultiplier(cost, result.upstreamPriceFactor()) +} + // calculateRecordUsageCost 根据请求类型计算费用。 func (s *GatewayService) calculateRecordUsageCost( ctx context.Context, @@ -1026,7 +1034,9 @@ func (s *GatewayService) calculateRecordUsageCost( if result.ImageCount > 0 { if !imageCountBillingApplies(apiKey, result.ImageEndpoint) { if resolved := s.resolveChannelPricing(ctx, billingModel, apiKey); resolved != nil && resolved.Mode == BillingModeToken { - return s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + tokenCost := s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + applyUpstreamPriceFactor(tokenCost, result) + return tokenCost } } return s.calculateImageCost(ctx, result, apiKey, billingModel, imageMultiplier) @@ -1057,6 +1067,7 @@ func (s *GatewayService) calculateRecordUsageCost( tokenCost = &CostBreakdown{} } else { tokenCost = s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + applyUpstreamPriceFactor(tokenCost, result) } if result.SearchCount > 0 { price := groupSearchPricePer1kFromAPIKey(apiKey) diff --git a/backend/internal/service/gemini_cached_content_test.go b/backend/internal/service/gemini_cached_content_test.go index e3afbdd5e6..2a07968279 100644 --- a/backend/internal/service/gemini_cached_content_test.go +++ b/backend/internal/service/gemini_cached_content_test.go @@ -387,6 +387,66 @@ func TestGeminiCachedContentStoragePricingAndSurcharge(t *testing.T) { require.InDelta(t, storage*1.5, storageOnly.ActualCost, 1e-12) } +// Scenario: 上游端点价格倍数只放大 token 费用,显式缓存存储费按原价叠加。 +func TestUpstreamPriceMultiplierScalesTokenCostOnly(t *testing.T) { + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(`{"gemini-3.7-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075, + "output_cost_per_token":0.00000375,"cache_read_input_token_cost":0.000000075,"cache_storage_cost_per_token_per_hour":0.000001}}`)) + require.NoError(t, err) + pricing.pricingData = data + gateway := &GatewayService{billingService: NewBillingService(&config.Config{}, pricing)} + groupID := int64(3) + apiKey := &APIKey{GroupID: &groupID, Group: &Group{ID: groupID, Hydrated: true}} + + const ( + inputTokens = 10000 + outputTokens = 1000 + cacheTokens = 5000 + tokenHours = 20000.0 + ) + baseInput := inputTokens * 0.00000075 + baseOutput := outputTokens * 0.00000375 + baseCacheRead := cacheTokens * 0.000000075 + storage := tokenHours * 0.000001 + + cost := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", + Usage: ClaudeUsage{InputTokens: inputTokens, OutputTokens: outputTokens, CacheReadInputTokens: cacheTokens}, + CacheStorageTokenHours: tokenHours, + UpstreamPriceMultiplier: 1.1, + }, apiKey, "gemini-3.7-flash", 2, 2, time.Now()) + require.InDelta(t, baseInput*1.1, cost.InputCost, 1e-12) + require.InDelta(t, baseOutput*1.1, cost.OutputCost, 1e-12) + require.InDelta(t, baseCacheRead*1.1, cost.CacheReadCost, 1e-12) + tokenTotal := (baseInput + baseOutput + baseCacheRead) * 1.1 + require.InDelta(t, tokenTotal+storage, cost.TotalCost, 1e-12) + require.InDelta(t, (tokenTotal+storage)*2, cost.ActualCost, 1e-12) + + unset := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", + Usage: ClaudeUsage{InputTokens: inputTokens, OutputTokens: outputTokens, CacheReadInputTokens: cacheTokens}, + }, apiKey, "gemini-3.7-flash", 1, 1, time.Now()) + require.InDelta(t, baseInput+baseOutput+baseCacheRead, unset.TotalCost, 1e-12) + + storageOnly := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", + CacheStorageTokenHours: tokenHours, + UpstreamPriceMultiplier: 1.1, + }, apiKey, "gemini-3.7-flash", 1, 1, time.Now()) + require.InDelta(t, storage, storageOnly.TotalCost, 1e-12) +} + +func TestApplyUpstreamPriceFactorTokenModeOnly(t *testing.T) { + result := &ForwardResult{UpstreamPriceMultiplier: 1.1} + for mode, want := range map[string]float64{"": 1.1, string(BillingModeToken): 1.1, string(BillingModePerRequest): 1, string(BillingModeImage): 1} { + cost := &CostBreakdown{InputCost: 1, TotalCost: 1, ActualCost: 1, BillingMode: mode} + applyUpstreamPriceFactor(cost, result) + require.InDelta(t, want, cost.TotalCost, 1e-12, mode) + require.InDelta(t, want, cost.ActualCost, 1e-12, mode) + } + applyUpstreamPriceFactor(nil, result) +} + func TestGeminiCachedContentStorageCostInAccountStats(t *testing.T) { const ( model = "gemini-3.8-flash" diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index d40b8a6e85..8bf3c96ae3 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -314,6 +314,8 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( ImageSize: imageSize, ImageInputSize: imageInputSize, ClientDisconnect: clientDisconnect, + + UpstreamPriceMultiplier: VertexUpstreamPriceMultiplier(account, mappedModel, ""), }, nil } diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 861a08ad12..f088aa648b 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -1081,6 +1081,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex ImageCount: imageCount, ImageSize: imageSize, ImageInputSize: imageInputSize, + UpstreamPriceMultiplier: VertexUpstreamPriceMultiplier(account, mappedModel, ""), }, nil } @@ -1147,6 +1148,8 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. var requestIDHeader string var buildReq func(ctx context.Context) (*http.Request, string, error) + // cachedContentLocation 是 Vertex 账号请求引用的显式缓存所在区域,未引用时为空。 + var cachedContentLocation string switch account.Type { case AccountTypeAPIKey: @@ -1247,7 +1250,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. requestIDHeader = "x-request-id" case AccountTypeServiceAccount: - cachedContentLocation := geminiCachedContentLocationInBody(body) + cachedContentLocation = geminiCachedContentLocationInBody(body) buildReq = func(ctx context.Context) (*http.Request, string, error) { fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, upstreamAction, useUpstreamStream, cachedContentLocation) if err != nil { @@ -1619,6 +1622,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. ImageCount: imageCount, ImageSize: imageSize, ImageInputSize: imageInputSize, + UpstreamPriceMultiplier: VertexUpstreamPriceMultiplier(account, mappedModel, cachedContentLocation), }, nil } diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go index f405a3a065..6fa8f8db8f 100644 --- a/backend/internal/service/gemini_vertex_api_key_forward_test.go +++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go @@ -176,6 +176,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model string body string want string + wantPrice float64 }{ { name: "supported model uses multi-region endpoint", @@ -184,6 +185,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.7-flash", body: `{` + contents + `}`, want: "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1.1, }, { name: "unsupported model falls back to global", @@ -192,6 +194,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.1-pro-preview", body: `{` + contents + `}`, want: "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3.1-pro-preview:generateContent", + wantPrice: 1, }, { name: "global cached content on multi-region account stays on global", @@ -200,6 +203,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.7-flash", body: `{"cachedContent":"projects/my-project/locations/global/cachedContents/42",` + contents + `}`, want: "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1, }, { name: "multi-region cached content on global account uses its region", @@ -208,13 +212,15 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.7-flash", body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, want: "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1.1, }, { - name: "express mode ignores cached content region", - location: "us", - model: "gemini-3.7-flash", - body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, - want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.7-flash:generateContent", + name: "express mode ignores cached content region", + location: "us", + model: "gemini-3.7-flash", + body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, + want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1, }, } for _, tc := range cases { @@ -224,10 +230,40 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte account := geminiVertexAPIKeyTestAccount(tc.projectID) account.Credentials["location"] = tc.location - _, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, []byte(tc.body)) + result, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, []byte(tc.body)) require.NoError(t, err) require.Equal(t, 1, httpStub.calls) require.Equal(t, tc.want, httpStub.lastReq.URL.String()) + require.InDelta(t, tc.wantPrice, result.UpstreamPriceMultiplier, 1e-12) }) } } + +// Scenario: Claude 兼容与 Chat 兼容入口经多区域账号发往 us 端点时,转发结果带多区域价格倍数。 +func TestGeminiCompatForwards_VertexMultiRegionSetsUpstreamPriceMultiplier(t *testing.T) { + gin.SetMode(gin.TestMode) + const want = "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent" + usAccount := func() *Account { + account := geminiVertexAPIKeyTestAccount("my-project") + account.Credentials["location"] = "us" + return account + } + + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + result, err := svc.Forward(context.Background(), c, usAccount(), + []byte(`{"model":"gemini-3.7-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)) + require.NoError(t, err) + require.Equal(t, want, httpStub.lastReq.URL.String()) + require.InDelta(t, 1.1, result.UpstreamPriceMultiplier, 1e-12) + + svc, httpStub = newGeminiVertexAPIKeyTestService() + body := []byte(`{"model":"gemini-3.7-flash","messages":[{"role":"user","content":"hi"}]}`) + c, _ = gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + result, err = svc.ForwardAsChatCompletions(context.Background(), c, usAccount(), body) + require.NoError(t, err) + require.Equal(t, want, httpStub.lastReq.URL.String()) + require.InDelta(t, 1.1, result.UpstreamPriceMultiplier, 1e-12) +} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index f3516aad1a..e77efee7e7 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -492,7 +492,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService, account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model, tokens, cost.TotalCost, pricingAt, - accountStatsLongContextPricingEnabled(longContextBillingGate) && !modelLongContextExempt, + accountStatsLongContextPricingEnabled(longContextBillingGate) && !modelLongContextExempt, 1, ) } diff --git a/backend/internal/service/vertex_locations.go b/backend/internal/service/vertex_locations.go index efc8fa1162..fa80348233 100644 --- a/backend/internal/service/vertex_locations.go +++ b/backend/internal/service/vertex_locations.go @@ -9,6 +9,9 @@ const ( vertexGlobalLocation = "global" vertexLocationUS = "us" vertexLocationEU = "eu" + + // vertexMultiRegionPriceMultiplier 是 vertexModelLocations 内的模型走多区域端点时相对 global 价的倍数。 + vertexMultiRegionPriceMultiplier = 1.1 ) // vertexModelLocations 列出 Vertex Gemini 模型可用的区域。Gemini 账号区域配置为多区域(us/eu)时, @@ -43,16 +46,46 @@ func vertexAPIHost(location string) string { } } -// resolveVertexModelLocation 返回模型在账号区域下实际使用的区域:账号为多区域而模型不支持该多区域时用 global。 -func resolveVertexModelLocation(accountLocation, model string) string { - if !isVertexMultiRegion(accountLocation) { - return accountLocation +// vertexModelSupportsMultiRegion 判断模型是否在 vertexModelLocations 中声明支持该多区域。 +func vertexModelSupportsMultiRegion(model, location string) bool { + if !isVertexMultiRegion(location) { + return false } if i := strings.LastIndex(model, "/"); i >= 0 { model = model[i+1:] } - if slices.Contains(vertexModelLocations[strings.TrimSpace(model)], accountLocation) { - return accountLocation + return slices.Contains(vertexModelLocations[strings.TrimSpace(model)], location) +} + +// resolveVertexModelLocation 返回模型在账号区域下实际使用的区域:账号为多区域而模型不支持该多区域时用 global。 +func resolveVertexModelLocation(accountLocation, model string) string { + if isVertexMultiRegion(accountLocation) && !vertexModelSupportsMultiRegion(model, accountLocation) { + return vertexGlobalLocation } - return vertexGlobalLocation + return accountLocation +} + +// vertexGeminiRequestLocation 返回 Vertex Gemini 请求实际发往的区域:未配置 project_id 的 API Key 账号 +// 走 Express mode 全局端点;引用显式缓存时为缓存所在区域;其余按 VertexLocation(model)。 +func vertexGeminiRequestLocation(account *Account, model, cachedContentLocation string) string { + if account.IsVertexAPIKey() && account.VertexProjectID() == "" { + return vertexGlobalLocation + } + if cachedContentLocation != "" { + return cachedContentLocation + } + return account.VertexLocation(model) +} + +// VertexUpstreamPriceMultiplier 返回 Vertex Gemini 账号请求 model 时相对 global 价的倍数:请求发往多区域端点 +// 且模型在 vertexModelLocations 中声明支持该多区域时为 vertexMultiRegionPriceMultiplier,其余为 1。 +// cachedContentLocation 为请求引用的显式缓存所在区域,未引用时为空。 +func VertexUpstreamPriceMultiplier(account *Account, model, cachedContentLocation string) float64 { + if account == nil || account.Platform != PlatformGemini || !account.IsVertexServiceAccount() { + return 1 + } + if vertexModelSupportsMultiRegion(model, vertexGeminiRequestLocation(account, model, cachedContentLocation)) { + return vertexMultiRegionPriceMultiplier + } + return 1 } diff --git a/backend/internal/service/vertex_locations_test.go b/backend/internal/service/vertex_locations_test.go index 36aa37d308..bff46974fc 100644 --- a/backend/internal/service/vertex_locations_test.go +++ b/backend/internal/service/vertex_locations_test.go @@ -127,3 +127,33 @@ func TestBuildVertexBatchPredictionJobsEndpointMultiRegionHost(t *testing.T) { require.NoError(t, err) require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/batchPredictionJobs", got) } + +func TestVertexUpstreamPriceMultiplier(t *testing.T) { + gemini := func(creds map[string]any) *Account { + return &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: creds} + } + us := gemini(map[string]any{"project_id": "p1", "location": "us"}) + require.InDelta(t, 1.1, VertexUpstreamPriceMultiplier(us, "gemini-3.7-flash", ""), 1e-12) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(us, "gemini-3.1-pro-preview", ""), 1e-12) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(us, "gemini-3.7-flash", "global"), 1e-12) + + eu := gemini(map[string]any{"project_id": "p1", "location": "eu"}) + require.InDelta(t, 1.1, VertexUpstreamPriceMultiplier(eu, "gemini-3.5-flash-lite", ""), 1e-12) + + global := gemini(map[string]any{"project_id": "p1", "location": "global"}) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(global, "gemini-3.7-flash", ""), 1e-12) + require.InDelta(t, 1.1, VertexUpstreamPriceMultiplier(global, "gemini-3.7-flash", "us"), 1e-12) + + regional := gemini(map[string]any{"project_id": "p1", "location": "us-central1"}) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(regional, "gemini-3.7-flash", ""), 1e-12) + + express := gemini(map[string]any{"auth_mode": "apikey", "api_key": "k", "location": "us"}) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(express, "gemini-3.7-flash", ""), 1e-12) + + aiStudio := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"location": "us"}} + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(aiStudio, "gemini-3.7-flash", ""), 1e-12) + + anthropic := &Account{Platform: PlatformAnthropic, Type: AccountTypeServiceAccount, Credentials: map[string]any{"location": "us"}} + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(anthropic, "gemini-3.7-flash", ""), 1e-12) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(nil, "gemini-3.7-flash", ""), 1e-12) +} diff --git a/backend/internal/service/vertex_service_account.go b/backend/internal/service/vertex_service_account.go index 6486791cf2..cd373afc11 100644 --- a/backend/internal/service/vertex_service_account.go +++ b/backend/internal/service/vertex_service_account.go @@ -345,10 +345,7 @@ func buildVertexGeminiAccountURL(account *Account, model, action string, stream if account.IsVertexAPIKey() && account.VertexProjectID() == "" { return buildVertexGeminiExpressURL(model, action, stream) } - location := cachedContentLocation - if location == "" { - location = account.VertexLocation(model) - } + location := vertexGeminiRequestLocation(account, model, cachedContentLocation) return buildVertexGeminiURL(account.VertexProjectID(), location, model, action, stream) } From b0d60a8c867b54919bccdb6dca8eb86dde2644b5 Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:30:23 +0800 Subject: [PATCH 75/85] fix(gemini): separate same-name parallel tool calls in streams --- .../gemini_chat_completions_compat_service.go | 4 +- .../service/gemini_messages_compat_service.go | 4 +- .../service/gemini_parallel_tools_test.go | 169 ++++++++++++++++++ .../service/gemini_tool_call_boundary.go | 25 +++ 4 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 backend/internal/service/gemini_parallel_tools_test.go create mode 100644 backend/internal/service/gemini_tool_call_boundary.go diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index f0716e003c..fc33c52d1b 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -600,6 +600,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom var seenThought geminiTextDelta openToolIndex := -1 openToolName := "" + openToolUpstreamID := "" var seenToolJSON geminiTextDelta closeOpenBlock := func() bool { @@ -735,7 +736,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom if closeOpenBlock() { return streamResult(), nil } - if openToolIndex >= 0 && openToolName != name { + if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { if closeOpenTool() { return streamResult(), nil } @@ -745,6 +746,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom nextBlockIndex++ openToolIndex = idx openToolName = name + openToolUpstreamID, _ = fc["id"].(string) sawToolUse = true if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_start", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 9d2ad1ae45..c1f10a793a 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2215,6 +2215,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex := -1 openToolID := "" openToolName := "" + openToolUpstreamID := "" var seenToolJSON geminiTextDelta reader := newBoundedSSELineReader(resp.Body, s.cfg) @@ -2394,7 +2395,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } // If we receive streamed tool args in pieces, keep a single tool block open and emit deltas. - if openToolIndex >= 0 && openToolName != name { + if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { writeSSE(c.Writer, "content_block_stop", map[string]any{ "type": "content_block_stop", "index": openToolIndex, @@ -2408,6 +2409,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolID = "toolu_" + randomHex(8) openToolIndex = nextBlockIndex openToolName = name + openToolUpstreamID, _ = fc["id"].(string) nextBlockIndex++ sawToolUse = true diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go new file mode 100644 index 0000000000..192887c579 --- /dev/null +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -0,0 +1,169 @@ +package service + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGeminiParallelToolStreams(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + frames [][]string + want []string + }{ + {"same_name_distinct_ids_one_event", [][]string{{`{"id":"a","name":"read_file","args":{"path":"a"}}`, `{"id":"b","name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_distinct_ids_separate_events", [][]string{{`{"id":"a","name":"read_file","args":{"path":"a"}}`}, {`{"id":"b","name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_identical_arguments_distinct_ids", [][]string{{`{"id":"a","name":"read_file","args":{}}`, `{"id":"b","name":"read_file","args":{}}`}}, []string{`{}`, `{}`}}, + {"same_name_no_ids_one_event", [][]string{{`{"name":"read_file","args":{"path":"a"}}`, `{"name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_no_ids_identical_separate_events", [][]string{{`{"name":"read_file","args":{}}`}, {`{"name":"read_file","args":{}}`}}, []string{`{}`, `{}`}}, + {"same_id_incremental_strings", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"no_id_incremental_strings", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"same_id_cumulative_and_duplicate", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, + } + for _, tt := range tests { + for _, protocol := range []string{"chat", "messages"} { + t.Run(tt.name+"/"+protocol, func(t *testing.T) { + var upstream strings.Builder + for _, frame := range tt.frames { + parts := []any{} + for _, fc := range frame { + var call map[string]any + require.NoError(t, json.Unmarshal([]byte(fc), &call)) + parts = append(parts, map[string]any{"functionCall": call}) + } + b, err := json.Marshal(map[string]any{"candidates": []any{map[string]any{"content": map[string]any{"parts": parts}}}}) + require.NoError(t, err) + upstream.WriteString("data: " + string(b) + "\n\n") + } + upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + svc := &GeminiMessagesCompatService{} + resp := &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(upstream.String()))} + var result *geminiStreamResult + var err error + if protocol == "chat" { + result, err = svc.handleChatCompletionsStreamingResponseFromGemini(c, resp, time.Now(), "gemini-test", false, true) + } else { + result, err = svc.handleStreamingResponse(c, resp, time.Now(), "gemini-test") + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.CacheReadInputTokens) + calls, terminal, open := collectParallelToolCalls(t, rec.Body.String(), protocol) + require.True(t, terminal) + require.Equal(t, -1, open) + require.Len(t, calls, len(tt.want)) + ids := map[string]bool{} + for i, want := range tt.want { + a := calls[i] + require.NotNil(t, a) + require.NotEmpty(t, a.id) + require.NotEmpty(t, a.name) + require.False(t, ids[a.id]) + ids[a.id] = true + require.JSONEq(t, want, a.args) + } + }) + } + } +} + +// collectParallelToolCalls checks the public SSE representation, including +// per-call metadata and the Anthropic content block lifecycle. +func collectParallelToolCalls(t *testing.T, body, protocol string) (map[int]*parallelToolCall, bool, int) { + t.Helper() + calls := map[int]*parallelToolCall{} + terminal, open := false, -1 + for _, line := range strings.Split(body, "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + raw := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if raw == "[DONE]" { + continue + } + var e struct { + Type string `json:"type"` + Index int `json:"index"` + ContentBlock struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + } `json:"content_block"` + Delta struct { + Type string `json:"type"` + PartialJSON string `json:"partial_json"` + StopReason string `json:"stop_reason"` + } `json:"delta"` + Choices []struct { + FinishReason string `json:"finish_reason"` + Delta struct { + ToolCalls []struct { + Index *int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + } + require.NoError(t, json.Unmarshal([]byte(raw), &e)) + if protocol == "chat" { + for _, choice := range e.Choices { + if choice.FinishReason == "tool_calls" { + terminal = true + } + for _, tc := range choice.Delta.ToolCalls { + require.NotNil(t, tc.Index) + idx := *tc.Index + a := calls[idx] + if a == nil { + require.NotEmpty(t, tc.ID, "first delta must identify its call") + require.NotEmpty(t, tc.Function.Name, "first delta must name its function") + a = ¶llelToolCall{} + calls[idx] = a + } + a.id += tc.ID + a.name += tc.Function.Name + a.args += tc.Function.Arguments + } + } + continue + } + switch e.Type { + case "content_block_start": + require.Equal(t, -1, open, "previous block must close before the next starts") + require.Equal(t, "tool_use", e.ContentBlock.Type) + open = e.Index + _, exists := calls[e.Index] + require.False(t, exists, "tool block indexes must be unique") + calls[e.Index] = ¶llelToolCall{id: e.ContentBlock.ID, name: e.ContentBlock.Name} + case "content_block_delta": + require.Equal(t, open, e.Index) + require.Equal(t, "input_json_delta", e.Delta.Type) + require.NotNil(t, calls[e.Index]) + calls[e.Index].args += e.Delta.PartialJSON + case "content_block_stop": + require.Equal(t, open, e.Index) + open = -1 + case "message_delta": + terminal = e.Delta.StopReason == "tool_use" + } + } + return calls, terminal, open +} + +type parallelToolCall struct{ id, name, args string } diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go new file mode 100644 index 0000000000..22f9914cdf --- /dev/null +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -0,0 +1,25 @@ +package service + +import ( + "encoding/json" + "strings" +) + +// geminiToolCallStartsNewBlock distinguishes call identity from function name. +// Calls with explicit IDs may contain incremental or cumulative arguments. +// Without IDs on both parts, a complete argument document marks the boundary +// before the next call, even when its name and arguments are identical. +func geminiToolCallStartsNewBlock(openID, openName, seenJSON string, fc map[string]any) bool { + name, _ := fc["name"].(string) + if strings.TrimSpace(name) == "" { + name = "tool" + } + if name != openName { + return true + } + id, _ := fc["id"].(string) + if id != "" && openID != "" { + return id != openID + } + return json.Valid([]byte(seenJSON)) +} From 27a61be4c9e72857fcde5b0d6085d31bdb73d10b Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:52:06 +0800 Subject: [PATCH 76/85] fix(gemini): preserve final snapshots of fragmented tool calls --- .../gemini_chat_completions_compat_service.go | 20 ++----- .../service/gemini_messages_compat_service.go | 25 +++----- .../service/gemini_parallel_tools_test.go | 13 +++- .../service/gemini_tool_call_boundary.go | 59 ++++++++++++++++--- 4 files changed, 74 insertions(+), 43 deletions(-) diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index fc33c52d1b..e89587866d 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -600,7 +600,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom var seenThought geminiTextDelta openToolIndex := -1 openToolName := "" - openToolUpstreamID := "" + var toolBoundary geminiToolCallBoundary var seenToolJSON geminiTextDelta closeOpenBlock := func() bool { @@ -620,6 +620,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} return disconnected } @@ -736,7 +737,8 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom if closeOpenBlock() { return streamResult(), nil } - if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { + argsJSONText := geminiToolCallArgsJSON(fc["args"]) + if openToolIndex >= 0 && toolBoundary.startsNewBlock(openToolName, seenToolJSON.seen.String(), argsJSONText, fc) { if closeOpenTool() { return streamResult(), nil } @@ -746,7 +748,6 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom nextBlockIndex++ openToolIndex = idx openToolName = name - openToolUpstreamID, _ = fc["id"].(string) sawToolUse = true if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_start", @@ -762,19 +763,8 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom } } - argsJSONText := "{}" - switch v := fc["args"].(type) { - case nil: - case string: - if strings.TrimSpace(v) != "" { - argsJSONText = v - } - default: - if b, err := json.Marshal(v); err == nil && len(b) > 0 { - argsJSONText = string(b) - } - } delta := seenToolJSON.next(argsJSONText) + toolBoundary.observe(fc, seenToolJSON.seen.String()) if delta != "" { if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_delta", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index c1f10a793a..b0e6b308cd 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2215,7 +2215,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex := -1 openToolID := "" openToolName := "" - openToolUpstreamID := "" + var toolBoundary geminiToolCallBoundary var seenToolJSON geminiTextDelta reader := newBoundedSSELineReader(resp.Body, s.cfg) @@ -2283,6 +2283,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } if openBlockType != "thinking" { if openBlockIndex >= 0 { @@ -2334,6 +2335,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } delta := seenText.next(text) @@ -2379,7 +2381,6 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re if fc, ok := part["functionCall"].(map[string]any); ok && fc != nil { name, _ := fc["name"].(string) - args := fc["args"] if strings.TrimSpace(name) == "" { name = "tool" } @@ -2395,7 +2396,8 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } // If we receive streamed tool args in pieces, keep a single tool block open and emit deltas. - if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { + argsJSONText := geminiToolCallArgsJSON(fc["args"]) + if openToolIndex >= 0 && toolBoundary.startsNewBlock(openToolName, seenToolJSON.seen.String(), argsJSONText, fc) { writeSSE(c.Writer, "content_block_stop", map[string]any{ "type": "content_block_stop", "index": openToolIndex, @@ -2403,13 +2405,13 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } if openToolIndex < 0 { openToolID = "toolu_" + randomHex(8) openToolIndex = nextBlockIndex openToolName = name - openToolUpstreamID, _ = fc["id"].(string) nextBlockIndex++ sawToolUse = true @@ -2425,21 +2427,8 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re }) } - argsJSONText := "{}" - switch v := args.(type) { - case nil: - // keep default "{}" - case string: - if strings.TrimSpace(v) != "" { - argsJSONText = v - } - default: - if b, err := json.Marshal(args); err == nil && len(b) > 0 { - argsJSONText = string(b) - } - } - delta := seenToolJSON.next(argsJSONText) + toolBoundary.observe(fc, seenToolJSON.seen.String()) if delta != "" { writeSSE(c.Writer, "content_block_delta", map[string]any{ "type": "content_block_delta", diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go index 192887c579..66babba3b2 100644 --- a/backend/internal/service/gemini_parallel_tools_test.go +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -28,6 +28,15 @@ func TestGeminiParallelToolStreams(t *testing.T) { {"same_id_incremental_strings", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, {"no_id_incremental_strings", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, {"same_id_cumulative_and_duplicate", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"anonymous_incremental_then_final_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"id_first_chunk_only_then_final_snapshot", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"id_learned_on_second_chunk_then_duplicate", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"same_name_no_ids_identical_one_event", [][]string{{`{"name":"read_file","args":{"path":"a"}}`, `{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_fragments_snapshot_then_identical_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_fragments_then_distinct_complete_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"late_id_then_distinct_same_arguments_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_cumulative_final_string_then_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"explicit_id_change_overrides_fragment_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":","id":"a"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, } for _, tt := range tests { @@ -43,9 +52,9 @@ func TestGeminiParallelToolStreams(t *testing.T) { } b, err := json.Marshal(map[string]any{"candidates": []any{map[string]any{"content": map[string]any{"parts": parts}}}}) require.NoError(t, err) - upstream.WriteString("data: " + string(b) + "\n\n") + _, _ = upstream.WriteString("data: " + string(b) + "\n\n") } - upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") + _, _ = upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) svc := &GeminiMessagesCompatService{} diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go index 22f9914cdf..9b2edd9a6e 100644 --- a/backend/internal/service/gemini_tool_call_boundary.go +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -5,11 +5,18 @@ import ( "strings" ) -// geminiToolCallStartsNewBlock distinguishes call identity from function name. -// Calls with explicit IDs may contain incremental or cumulative arguments. -// Without IDs on both parts, a complete argument document marks the boundary -// before the next call, even when its name and arguments are identical. -func geminiToolCallStartsNewBlock(openID, openName, seenJSON string, fc map[string]any) bool { +// geminiToolCallBoundary tracks identity separately from the function name. +// Native object-valued args without IDs represent independent calls, including +// identical calls. String-valued fragments may end with a cumulative snapshot; +// preserve that snapshot's identity until its object-valued args arrive. +// Without IDs, a terminal snapshot and a new identical call immediately after +// fragments are indistinguishable; prefer the snapshot in that specific case. +type geminiToolCallBoundary struct { + upstreamID string + fragmented bool +} + +func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON string, fc map[string]any) bool { name, _ := fc["name"].(string) if strings.TrimSpace(name) == "" { name = "tool" @@ -18,8 +25,44 @@ func geminiToolCallStartsNewBlock(openID, openName, seenJSON string, fc map[stri return true } id, _ := fc["id"].(string) - if id != "" && openID != "" { - return id != openID + if id != "" && b.upstreamID != "" { + return id != b.upstreamID } - return json.Valid([]byte(seenJSON)) + if !json.Valid([]byte(seenJSON)) { + return false + } + // Keep the existing delta accumulator's duplicate/rewind behavior for a + // fragmented call. Do not deduplicate separate complete native calls. + if b.fragmented && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { + return false + } + return true +} + +func (b *geminiToolCallBoundary) observe(fc map[string]any, seenJSON string) { + if b.upstreamID == "" { + b.upstreamID, _ = fc["id"].(string) + } + if _, isString := fc["args"].(string); isString { + b.fragmented = b.fragmented || !json.Valid([]byte(seenJSON)) + } else { + // The terminal object snapshot has been consumed. A following + // anonymous complete object can now be another identical call. + b.fragmented = false + } +} + +func geminiToolCallArgsJSON(args any) string { + switch v := args.(type) { + case nil: + case string: + if strings.TrimSpace(v) != "" { + return v + } + default: + if b, err := json.Marshal(args); err == nil && len(b) > 0 { + return string(b) + } + } + return "{}" } From ddb7eac6330af796c92e940f0112d34c36a24811 Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:13:53 +0800 Subject: [PATCH 77/85] chore(go): upgrade to 1.27.4 to resolve security check --- .github/workflows/backend-ci.yml | 4 ++-- .github/workflows/release.yml | 2 +- .github/workflows/security-scan.yml | 2 +- DEV_GUIDE.md | 2 +- Dockerfile | 2 +- backend/Dockerfile | 2 +- backend/go.mod | 2 +- deploy/Dockerfile | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index d1b420aa94..751f1fb0fd 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -35,7 +35,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Unit tests working-directory: backend run: make test-unit @@ -75,7 +75,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: golangci-lint uses: golangci/golangci-lint-action@v9 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9f2ef5dd7d..b5780a6be5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -137,7 +137,7 @@ jobs: check-latest: false cache: false - name: Verify Go version - run: go version | grep -q 'go1.27.3' + run: go version | grep -q 'go1.27.4' - name: Restore target-specific Go cache id: go-cache uses: actions/cache/restore@v6 diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 703e10354a..19893aae97 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -23,7 +23,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Run govulncheck working-directory: backend run: | diff --git a/DEV_GUIDE.md b/DEV_GUIDE.md index 2f440d0f62..f01d59e48c 100644 --- a/DEV_GUIDE.md +++ b/DEV_GUIDE.md @@ -53,7 +53,7 @@ npm install -g pnpm ### CI 要求 -- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 +- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 - 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml` ### 本地测试命令 diff --git a/Dockerfile b/Dockerfile index 0242d6f13e..0c9e438850 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.3-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.21 ARG POSTGRES_IMAGE=postgres:18-alpine ARG GOPROXY=https://goproxy.cn,direct diff --git a/backend/Dockerfile b/backend/Dockerfile index 40e228cd37..52bcb43dcc 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.2-alpine +FROM golang:1.27.4-alpine WORKDIR /app diff --git a/backend/go.mod b/backend/go.mod index 91db5d03b4..8163fbea14 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/Wei-Shaw/sub2api -go 1.27.3 +go 1.27.4 require ( entgo.io/ent v0.14.5 diff --git a/deploy/Dockerfile b/deploy/Dockerfile index d5c580b466..e0e8fbf030 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -7,7 +7,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.2-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.20 ARG GOPROXY=https://goproxy.cn,direct ARG GOSUMDB=sum.golang.google.cn From ce026a2cbf1e1d366ddd64fe098e8a0334949a7b Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:52:12 +0800 Subject: [PATCH 78/85] fix(gemini): retain complete string argument snapshots --- .../gemini_chat_completions_compat_service.go | 2 +- .../service/gemini_messages_compat_service.go | 2 +- .../service/gemini_parallel_tools_test.go | 8 ++++++ .../service/gemini_tool_call_boundary.go | 27 +++++++++---------- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index e89587866d..4626131b2e 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -764,7 +764,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom } delta := seenToolJSON.next(argsJSONText) - toolBoundary.observe(fc, seenToolJSON.seen.String()) + toolBoundary.observe(fc) if delta != "" { if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_delta", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index b0e6b308cd..4aee3e384d 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2428,7 +2428,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } delta := seenToolJSON.next(argsJSONText) - toolBoundary.observe(fc, seenToolJSON.seen.String()) + toolBoundary.observe(fc) if delta != "" { writeSSE(c.Writer, "content_block_delta", map[string]any{ "type": "content_block_delta", diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go index 66babba3b2..30145de0d3 100644 --- a/backend/internal/service/gemini_parallel_tools_test.go +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -37,6 +37,14 @@ func TestGeminiParallelToolStreams(t *testing.T) { {"late_id_then_distinct_same_arguments_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, {"anonymous_cumulative_final_string_then_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, {"explicit_id_change_overrides_fragment_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":","id":"a"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_duplicate_no_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_duplicate_first_id_only", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_duplicate_final_object_same_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"a"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_final_object_no_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"complete_strings_stable_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"a"}`}}, []string{`{"path":"a"}`}}, + {"complete_strings_distinct_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_snapshot_then_identical_native_call", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_late_id_then_new_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, } for _, tt := range tests { diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go index 9b2edd9a6e..5388e27e09 100644 --- a/backend/internal/service/gemini_tool_call_boundary.go +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -7,13 +7,13 @@ import ( // geminiToolCallBoundary tracks identity separately from the function name. // Native object-valued args without IDs represent independent calls, including -// identical calls. String-valued fragments may end with a cumulative snapshot; -// preserve that snapshot's identity until its object-valued args arrive. -// Without IDs, a terminal snapshot and a new identical call immediately after -// fragments are indistinguishable; prefer the snapshot in that specific case. +// identical calls. String-valued arguments use stream mode even when the first +// chunk is already complete JSON; retain duplicate strings and the terminal +// object snapshot in that call. Without IDs, a terminal snapshot and a new +// identical call after strings are indistinguishable; prefer the snapshot. type geminiToolCallBoundary struct { upstreamID string - fragmented bool + stringArgs bool } func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON string, fc map[string]any) bool { @@ -32,24 +32,21 @@ func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON str return false } // Keep the existing delta accumulator's duplicate/rewind behavior for a - // fragmented call. Do not deduplicate separate complete native calls. - if b.fragmented && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { + // string-argument call. Do not deduplicate separate complete native calls. + if b.stringArgs && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { return false } return true } -func (b *geminiToolCallBoundary) observe(fc map[string]any, seenJSON string) { +func (b *geminiToolCallBoundary) observe(fc map[string]any) { if b.upstreamID == "" { b.upstreamID, _ = fc["id"].(string) } - if _, isString := fc["args"].(string); isString { - b.fragmented = b.fragmented || !json.Valid([]byte(seenJSON)) - } else { - // The terminal object snapshot has been consumed. A following - // anonymous complete object can now be another identical call. - b.fragmented = false - } + // The representation determines the mode, not whether the first string + // happens to contain complete JSON. An object consumes the final snapshot, + // allowing the next anonymous native object to be an independent call. + _, b.stringArgs = fc["args"].(string) } func geminiToolCallArgsJSON(args any) string { From 9c3280098623989bac4d631fd8534d1c0e0ac672 Mon Sep 17 00:00:00 2001 From: feeeei Date: Sun, 15 Nov 2026 16:38:21 +0800 Subject: [PATCH 79/85] =?UTF-8?q?perf(scheduler):=20=E8=B0=83=E5=BA=A6?= =?UTF-8?q?=E5=BF=AB=E7=85=A7=E5=8A=A0=E8=BD=BD=E4=B8=8E=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E5=9B=9E=E6=BA=90=E6=8C=89=20bucket=20=E5=90=88?= =?UTF-8?q?=E5=B9=B6=EF=BC=8C=E5=87=8F=E5=B0=91=E5=A4=A7=E5=88=86=E7=BB=84?= =?UTF-8?q?=E9=80=89=E5=8F=B7=E7=9A=84=E6=95=B4=E7=BB=84=E5=A4=8D=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 分组账号数多时,进程内快照条目失效后每个并发请求各自 ZRANGE + MGET 全部精简记录并 逐个解码;Redis 读失败时每个请求又各自回源数据库并回写整份快照。每次选号还要把整组 账号按值复制三遍,并分块串行 MGET 全部 last_used。 - 快照条目加载按 (bucket, active, 修订号) 合并为一次,加载与调用方取消解耦; (active, 修订号) 未变、仅超过 10s 直接复用时长的条目在 20s 宽限期内先返回, 同时由一次后台加载刷新,修订号或 active 变化时仍等待新数据 - 重新加载时,精简记录原文未变且模型映射预解析对应当前运行时版本的账号沿用已解码母本 - last_used 读取结果在条目内复用 200ms,本进程写入 last_used 后立即失效; 多个分块的 MGET 放进同一个 pipeline 一次往返 - 新增 GetSnapshotValues 直接返回值切片,服务层优先使用,省掉 derefAccounts 的复制; 调度阈值过滤改为原地压缩 - 数据库回源按 bucket 合并:取发布令牌、读库与回写在一次共享调用里完成, 未配置 db_fallback_timeout_seconds 时上限 30s,各调用方得到独立的切片 压测(单用户 Bedrock、关闭在途预留):300 号 57.7K→61.6K RPM,500 号 42.3K→50.0K RPM。 --- .../internal/repository/scheduler_cache.go | 386 ++++++++++++++---- ...scheduler_cache_snapshot_memo_unit_test.go | 261 +++++++++++- backend/internal/service/account.go | 5 + .../internal/service/gateway_scheduling.go | 5 +- backend/internal/service/scheduler_cache.go | 7 + ...heduler_snapshot_fallback_coalesce_test.go | 191 +++++++++ .../service/scheduler_snapshot_service.go | 105 ++++- 7 files changed, 862 insertions(+), 98 deletions(-) create mode 100644 backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index f8a283d09f..63cc5e58d6 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -8,8 +8,10 @@ import ( "errors" "fmt" "log/slog" + "runtime/debug" "slices" "strconv" + "strings" "sync" "sync/atomic" "time" @@ -17,6 +19,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" "github.com/redis/go-redis/v9" "github.com/tidwall/gjson" + "golang.org/x/sync/singleflight" ) const ( @@ -35,7 +38,7 @@ const ( // 账号精简记录(sched:meta:)的修订号:全局修订号与按平台划分的修订号(前缀后接平台名)。 // 改写精简记录后写入所涉平台的修订号;删除记录、改写平台为空或平台发生变化的记录、写入出错时写入全局修订号。 // 取值都是新的随机串,读侧只比较是否相等,键丢失后重建也不会与旧取值相同; - // Redis 回滚恢复出缓存记录过的旧取值时,由最长复用时长兜底。 + // Redis 回滚恢复出缓存记录过的旧取值时,由进程内快照缓存的直接复用时长与宽限期兜底。 schedulerAccountMetaRevisionKey = "sched:meta:rev" schedulerAccountMetaPlatformRevisionPrefix = "sched:meta:rev:" @@ -47,12 +50,20 @@ const ( // 替代立即 DEL,让正在读取旧版本的 reader 有足够时间完成 ZRANGE。 snapshotGraceTTLSeconds = 60 - // schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的最长复用时长, - // 限定了未推进修订号的精简记录改写在本进程的最长可见延迟,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。 + // schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的直接复用时长,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。 + // 未推进修订号的精简记录改写在本进程的可见延迟不超过该时长与 schedulerSnapshotCacheStaleGrace 之和(另加一次加载耗时)。 schedulerSnapshotCacheMaxAge = 10 * time.Second + // schedulerSnapshotCacheStaleGrace:条目超过直接复用时长、但 (active, 修订号) 仍与 Redis 一致时, + // 在该宽限期内继续返回该条目,同时触发一次后台加载;超过宽限期后调用方等待加载结果。 + schedulerSnapshotCacheStaleGrace = 20 * time.Second // schedulerSnapshotCacheEvictAge:写入条目时,加载时间早于该时长的其它条目一并清除, // 已退休分组的条目不会长期驻留。 schedulerSnapshotCacheEvictAge = 10 * schedulerSnapshotCacheMaxAge + // schedulerLastUsedCacheMaxAge 是条目内 last_used 读取结果的复用时长;本进程写入 last_used 后该结果立即失效。 + schedulerLastUsedCacheMaxAge = 200 * time.Millisecond + // schedulerSharedLoadTimeout 是合并加载(快照条目、last_used)的上下文时限,约束取连接与重试; + // 单次套接字读取另受 Redis 客户端读超时约束。合并加载不随单个调用方取消。 + schedulerSharedLoadTimeout = 10 * time.Second schedulerAccountMetaRevisionBytes = 16 schedulerAccountMetaRevisionWriteTimeout = 3 * time.Second @@ -250,6 +261,10 @@ type schedulerCache struct { snapshotMu sync.RWMutex snapshotEntries map[string]*schedulerSnapshotEntry + // snapshotLoads 合并同一 bucket、同一组 (active, 修订号) 的条目加载。 + snapshotLoads singleflight.Group + // lastUsedGeneration 在本进程每次写入 last_used 后递增,条目内缓存的 last_used 读取结果随之失效。 + lastUsedGeneration atomic.Uint64 // globalRevisionPending 与 globalRevisionWriting 合并写入出错后的后台全局修订号写入,见 scheduleGlobalAccountMetaRevision。 globalRevisionPending atomic.Bool @@ -258,14 +273,38 @@ type schedulerCache struct { // schedulerSnapshotEntry 是一个 bucket 的已解码快照。 // revisions 依次是全局修订号与该 bucket 成员可能涉及的各平台修订号(见 schedulerSnapshotTagKeys)。 -// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄; +// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄;母本可以同时被多个条目引用。 +// ids、payloads、lastUsedKeys 与 accounts 一一对齐,payloads 是解码出母本的精简记录原文。 // 每次读取都按值复制出本次请求独占的副本再套用 last_used。 type schedulerSnapshotEntry struct { active string revisions []string loadedAt time.Time + ids []string accounts []*service.Account + payloads []string lastUsedKeys []string + + lastUsed atomic.Pointer[schedulerLastUsedValues] + lastUsedLoads singleflight.Group + // refreshing 在宽限期内的后台加载进行期间为 true,同一条目同时只发起一次后台加载。 + refreshing atomic.Bool +} + +// schedulerLastUsedValues 是条目的一次 last_used 读取结果,与条目的 accounts 一一对齐。 +// nil 表示沿用母本的 LastUsedAt;非 nil 的时间晚于母本,由各次读取共享,不得原地修改。 +type schedulerLastUsedValues struct { + fetchedAt time.Time + generation uint64 + values []*time.Time +} + +func (v *schedulerLastUsedValues) freshAt(now time.Time, generation uint64) bool { + if v == nil || v.generation != generation { + return false + } + age := now.Sub(v.fetchedAt) + return age >= 0 && age < schedulerLastUsedCacheMaxAge } func NewSchedulerCache(rdb *redis.Client) service.SchedulerCache { @@ -288,60 +327,141 @@ func newSchedulerCacheWithChunkSizes(rdb *redis.Client, mgetChunkSize, writeChun } } -// GetSnapshot 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存, -// 只有 ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过最长复用时长时才复用; -// 否则重新从 Redis 加载。last_used 每次都从 Redis 读取。 -// 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。 +// GetSnapshot 读取 bucket 的激活快照,语义与返回账号的使用约束同 GetSnapshotValues。 func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { + values, hit, err := c.GetSnapshotValues(ctx, bucket) + if err != nil || !hit { + return nil, false, err + } + accounts := make([]*service.Account, len(values)) + for i := range values { + accounts[i] = &values[i] + } + return accounts, true, nil +} + +// GetSnapshotValues 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存: +// ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过直接复用时长时直接复用; +// (active, 修订号) 一致但超过直接复用时长的条目在宽限期内继续返回,同时触发一次后台加载;其余情况等待加载结果。 +// 同一 bucket、同一组 (active, 修订号) 的并发加载合并为一次;加载时精简记录原文未变、 +// 且预解析结果对应当前运行时模型映射版本的账号沿用已解码的母本。 +// last_used 读取结果在条目内复用 schedulerLastUsedCacheMaxAge。 +// 返回的切片与其中的账号由本次调用独占,可以修改账号的顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。 +func (c *schedulerCache) GetSnapshotValues(ctx context.Context, bucket service.SchedulerBucket) ([]service.Account, bool, error) { + entry, err := c.snapshotEntry(ctx, bucket) + if err != nil { + return nil, false, err + } + if entry == nil { + return nil, false, nil + } + accounts, err := c.snapshotAccountsFromEntry(ctx, entry) + if err != nil { + return nil, false, err + } + return accounts, true, nil +} + +// snapshotEntry 返回 bucket 当前可用的条目;nil 表示快照未命中。 +func (c *schedulerCache) snapshotEntry(ctx context.Context, bucket service.SchedulerBucket) (*schedulerSnapshotEntry, error) { bucketKey := bucket.String() tagKeys := schedulerSnapshotTagKeys(bucket) tags, err := c.rdb.MGet(ctx, tagKeys...).Result() if err != nil { - return nil, false, err + return nil, err } if len(tags) != len(tagKeys) { - return nil, false, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys)) + return nil, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys)) } readyVal, err := schedulerCacheOptionalString(tags[0]) if err != nil { - return nil, false, err + return nil, err } activeVal, err := schedulerCacheOptionalString(tags[1]) if err != nil { - return nil, false, err + return nil, err } // 修订号缺失(nil)按空字符串比较:它是一个独立取值,不会与任何写入过的随机修订号相等。 revisions := make([]string, 0, len(tags)-2) for _, tag := range tags[2:] { revision, err := schedulerCacheOptionalString(tag) if err != nil { - return nil, false, err + return nil, err } revisions = append(revisions, revision) } if readyVal != "1" || activeVal == "" { c.dropSnapshotEntry(bucketKey) - return nil, false, nil + return nil, nil } now := c.now() - if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.matches(activeVal, revisions, now) { - accounts, err := c.snapshotAccountsFromEntry(ctx, entry) - if err != nil { - return nil, false, err + if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.sameVersion(activeVal, revisions) { + age := now.Sub(entry.loadedAt) + if age >= 0 && age < schedulerSnapshotCacheMaxAge { + return entry, nil + } + if age >= 0 && age < schedulerSnapshotCacheMaxAge+schedulerSnapshotCacheStaleGrace { + if entry.refreshing.CompareAndSwap(false, true) { + results := c.loadSnapshotEntryShared(ctx, bucket, bucketKey, activeVal, revisions, now) + go func() { + if result := <-results; result.Err != nil { + slog.Warn("scheduler snapshot background reload failed", "bucket", bucketKey, "error", result.Err) + } + entry.refreshing.Store(false) + }() + } + return entry, nil } - return accounts, true, nil } - ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVal), 0, -1).Result() + select { + case result := <-c.loadSnapshotEntryShared(ctx, bucket, bucketKey, activeVal, revisions, now): + if result.Err != nil { + return nil, result.Err + } + entry, _ := result.Val.(*schedulerSnapshotEntry) + return entry, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +// loadSnapshotEntryShared 发起或加入 bucket 在给定 (active, 修订号) 下的条目加载,结果的 Val 为 nil 表示快照未命中。 +// 加载使用与调用方取消解耦、时限为 schedulerSharedLoadTimeout 的上下文。 +func (c *schedulerCache) loadSnapshotEntryShared(ctx context.Context, bucket service.SchedulerBucket, bucketKey, active string, revisions []string, now time.Time) <-chan singleflight.Result { + key := bucketKey + "\x00" + active + "\x00" + strings.Join(revisions, "\x00") + loadCtx := context.WithoutCancel(ctx) + return c.snapshotLoads.DoChan(key, recoverSchedulerSharedLoad("scheduler snapshot load", func() (any, error) { + ctx, cancel := context.WithTimeout(loadCtx, schedulerSharedLoadTimeout) + defer cancel() + entry, err := c.loadSnapshotEntry(ctx, bucket, bucketKey, active, revisions, now) + if err != nil || entry == nil { + return nil, err + } + return entry, nil + })) +} + +// loadSnapshotEntry 从 Redis 加载条目并写入进程内缓存,返回 nil 表示快照未命中。 +// 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟 now:精简记录读取晚于这组取值, +// 之后若再有改写,修订号或 active 必然不同,或在直接复用时长与宽限期之和后不再返回。 +// 进程内已有同一 (active, 修订号) 且未过期的条目时直接返回它。 +func (c *schedulerCache) loadSnapshotEntry(ctx context.Context, bucket service.SchedulerBucket, bucketKey, active string, revisions []string, now time.Time) (*schedulerSnapshotEntry, error) { + previous := c.lookupSnapshotEntry(bucketKey) + if previous != nil && previous.matches(active, revisions, c.now()) { + return previous, nil + } + + ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, active), 0, -1).Result() if err != nil { - return nil, false, err + return nil, err } if len(ids) == 0 { // 空快照视为缓存未命中,触发数据库回退查询 // 这解决了新分组创建后立即绑定账号时的竞态条件问题 c.dropSnapshotEntry(bucketKey) - return nil, false, nil + return nil, nil } keys := make([]string, 0, len(ids)) @@ -352,74 +472,156 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul } values, err := c.mgetChunked(ctx, keys) if err != nil { - return nil, false, err + return nil, err + } + if len(values) != len(ids) { + return nil, fmt.Errorf("unexpected scheduler account metadata count: got %d, want %d", len(values), len(ids)) } - masters := make([]*service.Account, 0, len(values)) - for _, val := range values { + reusable := previous.masterIndex() + masters := make([]*service.Account, len(values)) + payloads := make([]string, len(values)) + for i, val := range values { if val == nil { c.dropSnapshotEntry(bucketKey) - return nil, false, nil + return nil, nil } - account, err := decodeCachedAccount(val) + payload, err := schedulerCachePayload(val) if err != nil { - return nil, false, err + return nil, err } - masters = append(masters, account) - } - // 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。 - for _, master := range masters { - master.PrepareSharedSnapshot() + if j, ok := reusable[ids[i]]; ok && previous.payloads[j] == payload && previous.accounts[j].SharedSnapshotCurrent() { + masters[i] = previous.accounts[j] + payloads[i] = previous.payloads[j] + continue + } + account, err := decodeCachedAccountPayload(payload) + if err != nil { + return nil, err + } + // 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。 + account.PrepareSharedSnapshot() + masters[i] = account + payloads[i] = payload } - // 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟:精简记录读取晚于这组取值, - // 之后若再有改写,修订号或 active 必然不同,或在最长复用时长后过期。 entry := &schedulerSnapshotEntry{ - active: activeVal, + active: active, revisions: revisions, loadedAt: now, + ids: ids, accounts: masters, + payloads: payloads, lastUsedKeys: lastUsedKeys, } c.storeSnapshotEntry(bucketKey, entry) + return entry, nil +} - accounts, err := c.snapshotAccountsFromEntry(ctx, entry) - if err != nil { - return nil, false, err - } - return accounts, true, nil +func (e *schedulerSnapshotEntry) sameVersion(active string, revisions []string) bool { + return e.active == active && slices.Equal(e.revisions, revisions) } func (e *schedulerSnapshotEntry) matches(active string, revisions []string, now time.Time) bool { - if e.active != active || !slices.Equal(e.revisions, revisions) { + if !e.sameVersion(active, revisions) { return false } age := now.Sub(e.loadedAt) return age >= 0 && age < schedulerSnapshotCacheMaxAge } -// snapshotAccountsFromEntry 读取最新 last_used,并为本次调用一次性分配一组母本副本。 -func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]*service.Account, error) { - lastUsedValues, err := c.mgetChunked(ctx, entry.lastUsedKeys) +// masterIndex 返回账号 ID 到母本下标的映射;条目为 nil 或缺少原文时返回 nil。 +func (e *schedulerSnapshotEntry) masterIndex() map[string]int { + if e == nil || len(e.ids) == 0 || len(e.ids) != len(e.accounts) || len(e.ids) != len(e.payloads) { + return nil + } + index := make(map[string]int, len(e.ids)) + for i, id := range e.ids { + index[id] = i + } + return index +} + +// snapshotAccountsFromEntry 为本次调用一次性分配一组母本副本,并套用 last_used。 +func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]service.Account, error) { + lastUsed, err := c.entryLastUsed(ctx, entry) if err != nil { return nil, err } - if len(lastUsedValues) != len(entry.accounts) { - return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(lastUsedValues), len(entry.accounts)) - } - slab := make([]service.Account, len(entry.accounts)) - accounts := make([]*service.Account, len(entry.accounts)) + accounts := make([]service.Account, len(entry.accounts)) for i, master := range entry.accounts { - slab[i] = *master - account := &slab[i] - if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil { - return nil, err + accounts[i] = *master + if lastUsed[i] != nil { + accounts[i].LastUsedAt = lastUsed[i] } - accounts[i] = account } return accounts, nil } +// entryLastUsed 返回条目的 last_used 读取结果:结果未超过 schedulerLastUsedCacheMaxAge 且本进程此后未写入 last_used 时直接复用, +// 否则等待一次合并后的读取。 +func (c *schedulerCache) entryLastUsed(ctx context.Context, entry *schedulerSnapshotEntry) ([]*time.Time, error) { + generation := c.lastUsedGeneration.Load() + if current := entry.lastUsed.Load(); current.freshAt(c.now(), generation) { + return current.values, nil + } + loadCtx := context.WithoutCancel(ctx) + results := entry.lastUsedLoads.DoChan(strconv.FormatUint(generation, 10), recoverSchedulerSharedLoad("scheduler last_used load", func() (any, error) { + fetchedAt := c.now() + if current := entry.lastUsed.Load(); current.freshAt(fetchedAt, generation) { + return current, nil + } + ctx, cancel := context.WithTimeout(loadCtx, schedulerSharedLoadTimeout) + defer cancel() + raw, err := c.mgetChunked(ctx, entry.lastUsedKeys) + if err != nil { + return nil, err + } + if len(raw) != len(entry.accounts) { + return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(raw), len(entry.accounts)) + } + values := make([]*time.Time, len(raw)) + for i, value := range raw { + lastUsedAt, err := parseSchedulerLastUsed(value) + if err != nil { + return nil, err + } + if lastUsedAt != nil && (entry.accounts[i].LastUsedAt == nil || lastUsedAt.After(*entry.accounts[i].LastUsedAt)) { + values[i] = lastUsedAt + } + } + loaded := &schedulerLastUsedValues{fetchedAt: fetchedAt, generation: generation, values: values} + entry.lastUsed.Store(loaded) + return loaded, nil + })) + select { + case result := <-results: + if result.Err != nil { + return nil, result.Err + } + loaded, _ := result.Val.(*schedulerLastUsedValues) + if loaded == nil { + return nil, errors.New("scheduler last_used load returned no values") + } + return loaded.values, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +// recoverSchedulerSharedLoad 包装合并加载:加载 panic 时记录堆栈并转成错误交给全部等待方。 +func recoverSchedulerSharedLoad(name string, load func() (any, error)) func() (any, error) { + return func() (result any, err error) { + defer func() { + if recovered := recover(); recovered != nil { + slog.Error("scheduler shared load panicked", "load", name, "panic", recovered, "stack", string(debug.Stack())) + result, err = nil, fmt.Errorf("%s panicked: %v", name, recovered) + } + }() + return load() + } +} + func (c *schedulerCache) lookupSnapshotEntry(bucketKey string) *schedulerSnapshotEntry { c.snapshotMu.RLock() defer c.snapshotMu.RUnlock() @@ -846,6 +1048,8 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0) } _, err := pipe.Exec(ctx) + // 写入结束(含部分失败)后才推进本进程的代际:此后发起的 last_used 读取都排在写入之后。 + c.lastUsedGeneration.Add(1) return err } @@ -930,9 +1134,24 @@ func schedulerLastUsedMillis(value time.Time) (int64, error) { } func applySchedulerLastUsed(account *service.Account, value any) error { - if account == nil || value == nil { + if account == nil { return nil } + lastUsedAt, err := parseSchedulerLastUsed(value) + if err != nil { + return err + } + if lastUsedAt != nil && (account.LastUsedAt == nil || lastUsedAt.After(*account.LastUsedAt)) { + account.LastUsedAt = lastUsedAt + } + return nil +} + +// parseSchedulerLastUsed 解析 last_used 侧键的毫秒时间戳;键不存在(nil)时返回 nil。 +func parseSchedulerLastUsed(value any) (*time.Time, error) { + if value == nil { + return nil, nil + } var raw string switch typed := value.(type) { case string: @@ -940,31 +1159,38 @@ func applySchedulerLastUsed(account *service.Account, value any) error { case []byte: raw = string(typed) default: - return fmt.Errorf("unexpected last_used cache type: %T", value) + return nil, fmt.Errorf("unexpected last_used cache type: %T", value) } millis, err := strconv.ParseInt(raw, 10, 64) if err != nil { - return fmt.Errorf("invalid last_used cache value %q: %w", raw, err) + return nil, fmt.Errorf("invalid last_used cache value %q: %w", raw, err) } - lastUsedAt := time.UnixMilli(millis).UTC() - if account.LastUsedAt == nil || lastUsedAt.After(*account.LastUsedAt) { - account.LastUsedAt = ptrTime(lastUsedAt) - } - return nil + return ptrTime(time.UnixMilli(millis).UTC()), nil } func decodeCachedAccount(val any) (*service.Account, error) { - var payload []byte + payload, err := schedulerCachePayload(val) + if err != nil { + return nil, err + } + return decodeCachedAccountPayload(payload) +} + +// schedulerCachePayload 取出 Redis 返回的账号记录原文。 +func schedulerCachePayload(val any) (string, error) { switch raw := val.(type) { case string: - payload = []byte(raw) + return raw, nil case []byte: - payload = raw + return string(raw), nil default: - return nil, fmt.Errorf("unexpected account cache type: %T", val) + return "", fmt.Errorf("unexpected account cache type: %T", val) } +} + +func decodeCachedAccountPayload(payload string) (*service.Account, error) { var account service.Account - if err := json.Unmarshal(payload, &account); err != nil { + if err := json.Unmarshal([]byte(payload), &account); err != nil { return nil, err } return &account, nil @@ -975,7 +1201,7 @@ func decodeCachedAccount(val any) (*service.Account, error) { // 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。 // 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号, // 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值), -// 漏检由进程内快照缓存的最长复用时长兜底。 +// 漏检由进程内快照缓存的直接复用时长与宽限期兜底。 // 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。 func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) { if len(accounts) == 0 { @@ -1102,7 +1328,7 @@ func (c *schedulerCache) scheduleGlobalAccountMetaRevision(ctx context.Context) } // advanceGlobalAccountMetaRevision 单独写入新的全局修订号,使所有 bucket 的进程内快照失效。 -// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的最长复用时长兜底。 +// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的直接复用时长与宽限期兜底。 func (c *schedulerCache) advanceGlobalAccountMetaRevision(ctx context.Context) { writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), schedulerAccountMetaRevisionWriteTimeout) defer cancel() @@ -1135,21 +1361,29 @@ func (c *schedulerCache) mgetChunked(ctx context.Context, keys []string) ([]any, return []any{}, nil } - out := make([]any, 0, len(keys)) chunkSize := c.mgetChunkSize if chunkSize <= 0 { chunkSize = defaultSchedulerSnapshotMGetChunkSize } + if len(keys) <= chunkSize { + return c.rdb.MGet(ctx, keys...).Result() + } + // 多个分块的 MGET 放在同一个 pipeline 里,一次往返发出。 + pipe := c.rdb.Pipeline() + cmds := make([]*redis.SliceCmd, 0, (len(keys)+chunkSize-1)/chunkSize) for start := 0; start < len(keys); start += chunkSize { end := start + chunkSize if end > len(keys) { end = len(keys) } - part, err := c.rdb.MGet(ctx, keys[start:end]...).Result() - if err != nil { - return nil, err - } - out = append(out, part...) + cmds = append(cmds, pipe.MGet(ctx, keys[start:end]...)) + } + if _, err := pipe.Exec(ctx); err != nil { + return nil, err + } + out := make([]any, 0, len(keys)) + for _, cmd := range cmds { + out = append(out, cmd.Val()...) } return out, nil } diff --git a/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go b/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go index 9b3d92ea26..54cb3e898d 100644 --- a/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go +++ b/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/alicebob/miniredis/v2" "github.com/redis/go-redis/v9" @@ -219,8 +220,10 @@ func memoEntryCount(cache *schedulerCache) int { return len(cache.snapshotEntries) } -func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testing.T) { +func TestSchedulerCacheSnapshotMemoRepeatReadsFetchTagsAndExpiredLastUsed(t *testing.T) { cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now bucket := memoTestBucket(101) memoPublish(t, cache, bucket, memoTestAccount(1, "a"), memoTestAccount(2, "b"), memoTestAccount(3, "c")) @@ -228,9 +231,17 @@ func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testi first := memoRead(t, cache, bucket) require.Equal(t, 1, recorder.countPrefix("zrange ")) require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix)) + require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountLastUsedPrefix)) recorder.reset() second := memoRead(t, cache, bucket) + require.Equal(t, []string{ + "mget " + schedulerBucketKey(schedulerReadyPrefix, bucket), + }, recorder.recorded(), "last_used read within its max age is reused") + + clock.Advance(schedulerLastUsedCacheMaxAge) + recorder.reset() + memoRead(t, cache, bucket) require.Equal(t, []string{ "mget " + schedulerBucketKey(schedulerReadyPrefix, bucket), "mget " + schedulerLastUsedKey("1"), @@ -248,6 +259,8 @@ func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testi func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *testing.T) { ctx := context.Background() cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now bucket := memoTestBucket(102) embedded := time.Now().UTC().Truncate(time.Millisecond).Add(-time.Hour) account := memoTestAccount(11, "a") @@ -272,8 +285,9 @@ func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *tes second[0].Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "replaced"}} require.Equal(t, "replaced", second[0].GetMappedModel("claude-sonnet")) - // 删除 last_used 侧键(不改精简记录):若母本曾被套用 last_used,这里会读到 latest。 + // 删除 last_used 侧键(不改精简记录)并越过 last_used 复用时长:若母本曾被套用 last_used,这里会读到 latest。 require.NoError(t, cache.rdb.Del(ctx, schedulerLastUsedKey("11")).Err()) + clock.Advance(schedulerLastUsedCacheMaxAge) recorder.reset() third := memoRead(t, cache, bucket) require.Zero(t, recorder.countPrefix("zrange ")) @@ -660,6 +674,8 @@ func memoReadExpectHit(t *testing.T, cache *schedulerCache, recorder *schedulerC func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing.T) { ctx := context.Background() cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now geminiSingle := service.SchedulerBucket{GroupID: 201, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} gemini := memoTestAccountOn(service.PlatformGemini, 211, "gemini") memoPublish(t, cache, geminiSingle, gemini) @@ -672,7 +688,6 @@ func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing memoRead(t, cache, geminiSingle) require.Equal(t, []string{ "mget " + schedulerBucketKey(schedulerReadyPrefix, geminiSingle), - "mget " + schedulerLastUsedKey("211"), }, recorder.recorded(), "an Anthropic account write must not invalidate a Gemini bucket") gemini.Name = "gemini-renamed" @@ -844,8 +859,248 @@ func TestSchedulerCacheSnapshotMemoMaxAgeBoundsUnversionedWrites(t *testing.T) { clock.Advance(schedulerSnapshotCacheMaxAge - time.Millisecond) require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + // 超过直接复用时长:本次仍返回旧条目,同时由后台加载刷新。 clock.Advance(time.Millisecond) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + require.Eventually(t, func() bool { + accounts, hit, err := cache.GetSnapshot(ctx, bucket) + return err == nil && hit && accounts[0].Name == "new" + }, time.Second, 5*time.Millisecond) +} + +func TestSchedulerCacheSnapshotMemoStaleGraceIsBounded(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + bucket := memoTestBucket(127) + memoPublish(t, cache, bucket, memoTestAccount(152, "old")) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + + _, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(152, "new")) + require.NoError(t, err) + require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("152"), metaPayload, 0).Err()) + + // 超过直接复用时长与宽限期之和后,读取等待加载结果。 + clock.Advance(schedulerSnapshotCacheMaxAge + schedulerSnapshotCacheStaleGrace) + recorder.reset() require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name) + require.Equal(t, 1, recorder.countPrefix("zrange ")) +} + +func TestSchedulerCacheSnapshotMemoVersionChangeWaitsForReload(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + bucket := memoTestBucket(128) + account := memoTestAccount(153, "old") + memoPublish(t, cache, bucket, account) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + + // 条目已超过直接复用时长;修订号变化后不走宽限期,本次读取即看到新值。 + clock.Advance(schedulerSnapshotCacheMaxAge) + account.Name = "new" + require.NoError(t, cache.SetAccount(ctx, &account)) + require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name) +} + +// blockingZRangeHook 让 ZRANGE 停在 release 关闭之前。 +type blockingZRangeHook struct { + release chan struct{} +} + +func (h *blockingZRangeHook) DialHook(next redis.DialHook) redis.DialHook { return next } + +func (h *blockingZRangeHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if strings.EqualFold(cmd.Name(), "zrange") { + <-h.release + } + return next(ctx, cmd) + } +} + +func (h *blockingZRangeHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return next +} + +func TestSchedulerCacheSnapshotMemoConcurrentLoadsAreCoalesced(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(129) + memoPublish(t, cache, bucket, memoTestAccount(154, "a"), memoTestAccount(155, "b")) + hook := &blockingZRangeHook{release: make(chan struct{})} + cache.rdb.AddHook(hook) + recorder.reset() + + const readers = 16 + results := make(chan error, readers) + for i := 0; i < readers; i++ { + go func() { + accounts, hit, err := cache.GetSnapshot(ctx, bucket) + if err == nil && (!hit || len(accounts) != 2) { + err = fmt.Errorf("hit=%v accounts=%d", hit, len(accounts)) + } + results <- err + }() + } + readyKey := "mget " + schedulerBucketKey(schedulerReadyPrefix, bucket) + require.Eventually(t, func() bool { return recorder.countPrefix(readyKey) == readers }, time.Second, time.Millisecond) + close(hook.release) + for i := 0; i < readers; i++ { + require.NoError(t, <-results) + } + require.Equal(t, 1, recorder.countPrefix("zrange ")) + require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix)) +} + +func TestSchedulerCacheSnapshotMemoCanceledWaiterDoesNotAbortSharedLoad(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(130) + memoPublish(t, cache, bucket, memoTestAccount(156, "a")) + hook := &blockingZRangeHook{release: make(chan struct{})} + cache.rdb.AddHook(hook) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, _, err := cache.GetSnapshot(ctx, bucket) + done <- err + }() + require.Eventually(t, func() bool { return recorder.countPrefix("zrange ") == 1 }, time.Second, time.Millisecond) + cancel() + require.ErrorIs(t, <-done, context.Canceled) + + close(hook.release) + require.Eventually(t, func() bool { return memoEntryCount(cache) == 1 }, time.Second, time.Millisecond) + require.Equal(t, []int64{156}, memoIDs(memoRead(t, cache, bucket))) +} + +func TestSchedulerCacheSnapshotMemoReloadReusesUnchangedMasters(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(131) + changed := memoTestAccount(158, "b") + memoPublish(t, cache, bucket, memoTestAccount(157, "a"), changed, memoTestAccount(159, "c")) + memoRead(t, cache, bucket) + before := cache.lookupSnapshotEntry(bucket.String()) + require.NotNil(t, before) + + changed.Name = "b2" + require.NoError(t, cache.SetAccount(ctx, &changed)) + got := memoRead(t, cache, bucket) + require.Equal(t, "b2", got[1].Name) + after := cache.lookupSnapshotEntry(bucket.String()) + require.NotSame(t, before, after) + require.Same(t, before.accounts[0], after.accounts[0]) + require.NotSame(t, before.accounts[1], after.accounts[1]) + require.Same(t, before.accounts[2], after.accounts[2]) + require.Equal(t, "b", before.accounts[1].Name, "reload must not modify the previous master") +} + +// 服务层按该方法签名探测值切片读取。 +var _ interface { + GetSnapshotValues(ctx context.Context, bucket service.SchedulerBucket) ([]service.Account, bool, error) +} = (*schedulerCache)(nil) + +func TestSchedulerCacheSnapshotMemoReloadRedecodesMastersAfterRuntimeMappingChange(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(134) + changed := memoTestAccount(167, "b") + memoPublish(t, cache, bucket, memoTestAccount(166, "a"), changed) + memoRead(t, cache, bucket) + before := cache.lookupSnapshotEntry(bucket.String()) + require.True(t, before.accounts[0].SharedSnapshotCurrent()) + + xai.SetRuntimeModelMappingOptions(xai.RuntimeModelMappingOptions()) + require.False(t, before.accounts[0].SharedSnapshotCurrent()) + changed.Name = "b2" + require.NoError(t, cache.SetAccount(ctx, &changed)) + memoRead(t, cache, bucket) + after := cache.lookupSnapshotEntry(bucket.String()) + require.NotSame(t, before.accounts[0], after.accounts[0], "a master prepared under an older runtime mapping version is decoded again") + require.True(t, after.accounts[0].SharedSnapshotCurrent()) +} + +func TestSchedulerCacheSnapshotMemoStaleEntryStartsOneBackgroundReload(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + bucket := memoTestBucket(135) + memoPublish(t, cache, bucket, memoTestAccount(168, "old")) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + stale := cache.lookupSnapshotEntry(bucket.String()) + + _, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(168, "new")) + require.NoError(t, err) + require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("168"), metaPayload, 0).Err()) + hook := &blockingZRangeHook{release: make(chan struct{})} + cache.rdb.AddHook(hook) + clock.Advance(schedulerSnapshotCacheMaxAge) + recorder.reset() + + for i := 0; i < 5; i++ { + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + } + require.True(t, stale.refreshing.Load()) + require.Eventually(t, func() bool { return recorder.countPrefix("zrange ") == 1 }, time.Second, time.Millisecond) + close(hook.release) + require.Eventually(t, func() bool { return !stale.refreshing.Load() }, time.Second, time.Millisecond) + require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name) + require.Equal(t, 1, recorder.countPrefix("zrange ")) +} + +func TestSchedulerCacheSnapshotMemoLastUsedWriteInvalidatesLocalCache(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + bucket := memoTestBucket(132) + memoPublish(t, cache, bucket, memoTestAccount(160, "a")) + require.Nil(t, memoRead(t, cache, bucket)[0].LastUsedAt) + + // 其它进程写入的 last_used 在复用时长内不可见。 + usedAt := time.Date(2026, 10, 20, 7, 0, 0, 0, time.UTC) + require.NoError(t, cache.rdb.Set(ctx, schedulerLastUsedKey("160"), strconv.FormatInt(usedAt.UnixMilli(), 10), 0).Err()) + require.Nil(t, memoRead(t, cache, bucket)[0].LastUsedAt) + + // 本进程写入 last_used 后立即可见。 + later := usedAt.Add(time.Minute) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{160: later})) + recorder.reset() + got := memoRead(t, cache, bucket) + require.Equal(t, later, *got[0].LastUsedAt) + require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountLastUsedPrefix)) + require.Zero(t, recorder.countPrefix("zrange ")) +} + +func TestSchedulerCacheSnapshotMemoChunkedMGetUsesOnePipeline(t *testing.T) { + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + recorder := &schedulerCacheCommandRecorder{} + rdb.AddHook(recorder) + cache, ok := newSchedulerCacheWithChunkSizes(rdb, 2, defaultSchedulerSnapshotWriteChunkSize).(*schedulerCache) + require.True(t, ok) + bucket := memoTestBucket(133) + accounts := make([]service.Account, 0, 5) + for id := int64(161); id <= 165; id++ { + accounts = append(accounts, memoTestAccount(id, strconv.FormatInt(id, 10))) + } + memoPublish(t, cache, bucket, accounts...) + + recorder.reset() + got := memoRead(t, cache, bucket) + require.Equal(t, []int64{161, 162, 163, 164, 165}, memoIDs(got)) + batches := recorder.pipelineBatches() + require.Len(t, batches, 2, "metadata and last_used each travel in one pipeline") + for _, batch := range batches { + require.Len(t, batch, 3) + } + require.Equal(t, 3, recorder.countPrefix("mget "+schedulerAccountMetaPrefix)) } func TestSchedulerCacheSnapshotMemoEvictsLongIdleEntries(t *testing.T) { diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 8899c2d70d..63fd809baf 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -677,6 +677,11 @@ func (a *Account) PrepareSharedSnapshot() { a.modelMappingCacheShared = true } +// SharedSnapshotCurrent 报告账号是否为 PrepareSharedSnapshot 处理过的母本,且其预解析结果对应当前的运行时模型映射版本。 +func (a *Account) SharedSnapshotCurrent() bool { + return a != nil && a.modelMappingCacheShared && a.modelMappingCacheRuntimeVersion == xai.RuntimeModelMappingVersion() +} + func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]string { if a.Credentials == nil { // Antigravity 平台使用默认映射 diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index b1219980e7..1060bbd0ec 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1548,18 +1548,21 @@ func (s *GatewayService) getSchedulableAccount(ctx context.Context, accountID in return account, nil } +// filterAccountsBySchedulingThreshold 在 accounts 上原地剔除被调度阈值暂停的账号并返回剔除后的切片; +// accounts 必须由调用方独占,调用后只能使用返回值。 func (s *GatewayService) filterAccountsBySchedulingThreshold(ctx context.Context, accounts []Account) []Account { if len(accounts) == 0 { return accounts } - filtered := make([]Account, 0, len(accounts)) + filtered := accounts[:0] for i := range accounts { if s.isAccountBlockedBySchedulingThreshold(ctx, &accounts[i]) { continue } filtered = append(filtered, accounts[i]) } + clear(accounts[len(filtered):]) return filtered } diff --git a/backend/internal/service/scheduler_cache.go b/backend/internal/service/scheduler_cache.go index 5e5dbed164..dd9e7f6dae 100644 --- a/backend/internal/service/scheduler_cache.go +++ b/backend/internal/service/scheduler_cache.go @@ -73,6 +73,13 @@ func ParseSchedulerBucket(raw string) (SchedulerBucket, bool) { }, true } +// schedulerSnapshotValuesReader 由能直接返回账号值切片的 SchedulerCache 实现。 +// GetSnapshotValues 与 GetSnapshot 读取同一份快照,返回的切片与其中的账号由本次调用独占, +// 账号的使用约束与 GetSnapshot 相同。 +type schedulerSnapshotValuesReader interface { + GetSnapshotValues(ctx context.Context, bucket SchedulerBucket) ([]Account, bool, error) +} + // SchedulerCache 负责调度快照与账号快照的缓存读写。 type SchedulerCache interface { // GetSnapshot 读取快照并返回命中与否(ready + active + 数据完整)。 diff --git a/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go b/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go new file mode 100644 index 0000000000..8049a93204 --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go @@ -0,0 +1,191 @@ +//go:build unit + +package service + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// fallbackCoalesceCache 总是快照未命中,并统计发布令牌与回写次数。 +type fallbackCoalesceCache struct { + SchedulerCache + reads atomic.Int32 + tokens atomic.Int32 + publish atomic.Int32 + snapshot []Account +} + +func (c *fallbackCoalesceCache) GetSnapshot(context.Context, SchedulerBucket) ([]*Account, bool, error) { + c.reads.Add(1) + return nil, false, nil +} + +func (c *fallbackCoalesceCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + c.tokens.Add(1) + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *fallbackCoalesceCache) SetSnapshot(_ context.Context, _ SchedulerBucket, _ SchedulerBucketWriteToken, accounts []Account) error { + c.publish.Add(1) + c.snapshot = accounts + return nil +} + +// fallbackCoalesceRepo 的分组查询停在 release 关闭之前,并统计调用次数。 +type fallbackCoalesceRepo struct { + AccountRepository + release chan struct{} + calls atomic.Int32 + accounts []Account +} + +func (r *fallbackCoalesceRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, _ string) ([]Account, error) { + r.calls.Add(1) + select { + case <-r.release: + case <-ctx.Done(): + return nil, ctx.Err() + } + return r.accounts, nil +} + +func newFallbackCoalesceService(cache SchedulerCache, repo AccountRepository) *SchedulerSnapshotService { + return NewSchedulerSnapshotService(cache, nil, repo, nil, &config.Config{ + RunMode: config.RunModeStandard, + Gateway: config.GatewayConfig{Scheduling: config.GatewaySchedulingConfig{ + DbFallbackEnabled: true, + }}, + }) +} + +func TestSchedulerFallbackConcurrentMissesShareOneDBLoad(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + cache := &fallbackCoalesceCache{} + repo := &fallbackCoalesceRepo{ + release: make(chan struct{}), + accounts: []Account{ + {ID: 7101, Name: "a", Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}, + {ID: 7102, Name: "b", Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}, + }, + } + svc := newFallbackCoalesceService(cache, repo) + groupID := int64(71) + + const callers = 12 + results := make([][]Account, callers) + errs := make([]error, callers) + var wg sync.WaitGroup + for i := 0; i < callers; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + results[i], _, errs[i] = svc.ListSchedulableAccounts(context.Background(), &groupID, PlatformOpenAI, false) + }(i) + } + synctest.Wait() + require.Equal(t, int32(callers), cache.reads.Load()) + require.Equal(t, int32(1), repo.calls.Load()) + close(repo.release) + wg.Wait() + + require.Equal(t, int32(1), repo.calls.Load()) + require.Equal(t, int32(1), cache.tokens.Load()) + require.Equal(t, int32(1), cache.publish.Load()) + for i := 0; i < callers; i++ { + require.NoError(t, errs[i]) + require.Len(t, results[i], 2) + } + + // 每个调用方的切片相互独立,也不与回写的快照共用底层数组。 + results[0][0].Name = "mutated" + results[0] = append(results[0][:1], Account{ID: 7199}) + for i := 1; i < callers; i++ { + require.Equal(t, "a", results[i][0].Name) + require.Equal(t, int64(7102), results[i][1].ID) + } + require.Equal(t, "a", cache.snapshot[0].Name) + require.Equal(t, int64(7102), cache.snapshot[1].ID) + }) +} + +func TestSchedulerFallbackCanceledWaiterLeavesSharedLoadRunning(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + cache := &fallbackCoalesceCache{} + repo := &fallbackCoalesceRepo{ + release: make(chan struct{}), + accounts: []Account{{ID: 7201, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}}, + } + svc := newFallbackCoalesceService(cache, repo) + groupID := int64(72) + + ctx, cancel := context.WithCancel(context.Background()) + canceled := make(chan error, 1) + go func() { + _, _, err := svc.ListSchedulableAccounts(ctx, &groupID, PlatformOpenAI, false) + canceled <- err + }() + synctest.Wait() + require.Equal(t, int32(1), repo.calls.Load()) + + joined := make(chan []Account, 1) + go func() { + accounts, _, err := svc.ListSchedulableAccounts(context.Background(), &groupID, PlatformOpenAI, false) + if err != nil { + accounts = nil + } + joined <- accounts + }() + synctest.Wait() + + cancel() + require.ErrorIs(t, <-canceled, context.Canceled) + close(repo.release) + accounts := <-joined + require.Len(t, accounts, 1) + require.Equal(t, int32(1), repo.calls.Load(), "the canceled caller must not abort the shared load") + require.Equal(t, int32(1), cache.publish.Load()) + }) +} + +// valuesReaderCache 直接返回值切片;GetSnapshot 不应被调用。 +type valuesReaderCache struct { + SchedulerCache + values []Account + snapshotCalls atomic.Int32 +} + +func (c *valuesReaderCache) GetSnapshotValues(context.Context, SchedulerBucket) ([]Account, bool, error) { + return c.values, true, nil +} + +func (c *valuesReaderCache) GetSnapshot(context.Context, SchedulerBucket) ([]*Account, bool, error) { + c.snapshotCalls.Add(1) + return nil, false, nil +} + +func TestSchedulerSnapshotListUsesValuesReaderWithoutCopy(t *testing.T) { + cache := &valuesReaderCache{values: []Account{{ID: 7301, Platform: PlatformOpenAI}, {ID: 7302, Platform: PlatformOpenAI}}} + svc := newFallbackCoalesceService(cache, nil) + groupID := int64(73) + + accounts, _, err := svc.ListSchedulableAccounts(context.Background(), &groupID, PlatformOpenAI, false) + require.NoError(t, err) + require.Len(t, accounts, 2) + require.Same(t, &cache.values[0], &accounts[0]) + require.Zero(t, cache.snapshotCalls.Load()) +} + +func TestFilterAccountsBySchedulingThresholdCompactsInPlace(t *testing.T) { + svc := &GatewayService{} + accounts := []Account{{ID: 1}, {ID: 2}, {ID: 3}} + filtered := svc.filterAccountsBySchedulingThreshold(context.Background(), accounts) + require.Equal(t, []int64{1, 2, 3}, []int64{filtered[0].ID, filtered[1].ID, filtered[2].ID}) + require.Same(t, &accounts[0], &filtered[0]) +} diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 2073ad0f53..f4173d47c3 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "log/slog" + "runtime/debug" "sort" "strconv" "sync" @@ -14,6 +15,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "golang.org/x/sync/singleflight" ) var ( @@ -23,6 +25,11 @@ var ( ErrSchedulerBucketRebuildBusy = errors.New("scheduler bucket rebuild busy") ) +const ( + // schedulerSharedFallbackTimeout 是合并回源在未配置 db_fallback_timeout_seconds 时的时长上限;合并回源不随单个调用方取消。 + schedulerSharedFallbackTimeout = 30 * time.Second +) + const ( outboxEventTimeout = 2 * time.Minute schedulerOutboxCleanupBatch = 5000 @@ -144,6 +151,9 @@ type SchedulerSnapshotService struct { fullRebuildRequested uint64 fullRebuildCompleted uint64 fullRebuildLastErr error + + // fallbackLoads 合并同一 bucket 的并发数据库回源。 + fallbackLoads singleflight.Group } func NewSchedulerSnapshotService( @@ -212,26 +222,82 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, useMixed := (platform == PlatformAnthropic || platform == PlatformGemini) && !hasForcePlatform mode := s.resolveMode(platform, hasForcePlatform) bucket := s.bucketFor(groupID, platform, mode) - var writeToken SchedulerBucketWriteToken - canPublish := false if err := ctx.Err(); err != nil { return nil, useMixed, err } if s.cache != nil { - cached, hit, err := s.cache.GetSnapshot(ctx, bucket) + cached, hit, err := s.readSnapshotAccounts(ctx, bucket) if ctxErr := ctx.Err(); ctxErr != nil { return nil, useMixed, ctxErr } if err != nil { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] cache read failed: bucket=%s err=%v", bucket.String(), err) } else if hit { - return derefAccounts(cached), useMixed, nil + return cached, useMixed, nil } + } + + accounts, err := s.loadFallbackAccounts(ctx, bucket, useMixed) + if err != nil { + return nil, useMixed, err + } + return accounts, useMixed, nil +} + +// readSnapshotAccounts 读取 bucket 快照;缓存实现能直接返回值切片时直接使用该切片。 +func (s *SchedulerSnapshotService) readSnapshotAccounts(ctx context.Context, bucket SchedulerBucket) ([]Account, bool, error) { + if reader, ok := s.cache.(schedulerSnapshotValuesReader); ok { + return reader.GetSnapshotValues(ctx, bucket) + } + cached, hit, err := s.cache.GetSnapshot(ctx, bucket) + if err != nil || !hit { + return nil, false, err + } + return derefAccounts(cached), true, nil +} + +// loadFallbackAccounts 回源数据库读取 bucket 的账号,取得发布令牌时尽力回写快照。 +// 同一 bucket 的并发回源合并为一次:合并回源与回写不随单个调用方取消,各调用方按自身 ctx 等待结果, +// 并各自得到一份独占的切片;账号的 map、切片底层数组与指针指向的值在调用方之间共享,不得原地修改。 +func (s *SchedulerSnapshotService) loadFallbackAccounts(ctx context.Context, bucket SchedulerBucket, useMixed bool) ([]Account, error) { + loadCtx := context.WithoutCancel(ctx) + results := s.fallbackLoads.DoChan(bucket.String(), func() (result any, err error) { + defer func() { + if recovered := recover(); recovered != nil { + slog.Error("scheduler db fallback panicked", "bucket", bucket.String(), "panic", recovered, "stack", string(debug.Stack())) + result, err = nil, fmt.Errorf("scheduler db fallback panicked: %v", recovered) + } + }() + return s.loadAndPublishFallback(loadCtx, bucket, useMixed) + }) + select { + case result := <-results: + if result.Err != nil { + return nil, result.Err + } + shared, _ := result.Val.([]Account) + if shared == nil { + return nil, nil + } + accounts := make([]Account, len(shared)) + copy(accounts, shared) + return accounts, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +// loadAndPublishFallback 先取发布令牌再读数据库:令牌之后发生的 Retire 会拦下这次回写。 +// 取令牌、读库与回写共用 withSharedFallbackTimeout 的时限。 +func (s *SchedulerSnapshotService) loadAndPublishFallback(ctx context.Context, bucket SchedulerBucket, useMixed bool) ([]Account, error) { + ctx, cancel := s.withSharedFallbackTimeout(ctx) + defer cancel() + + var writeToken SchedulerBucketWriteToken + canPublish := false + if s.cache != nil { token, err := s.cache.CaptureBucketWriteToken(ctx, bucket) - if ctxErr := ctx.Err(); ctxErr != nil { - return nil, useMixed, ctxErr - } if err != nil { if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) { slog.Debug("[Scheduler] cache publish fenced", "bucket", bucket.String()) @@ -245,22 +311,16 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, } if err := s.guardFallback(ctx); err != nil { - return nil, useMixed, err + return nil, err } - fallbackCtx, cancel := s.withFallbackTimeout(ctx) - defer cancel() - - accounts, err := s.loadAccountsFromDB(fallbackCtx, bucket, useMixed) + accounts, err := s.loadAccountsFromDB(ctx, bucket, useMixed) if err != nil { - return nil, useMixed, err - } - if ctxErr := ctx.Err(); ctxErr != nil { - return nil, useMixed, ctxErr + return nil, err } if s.cache != nil && canPublish { - if err := s.cache.SetSnapshot(fallbackCtx, bucket, writeToken, accounts); err != nil { + if err := s.cache.SetSnapshot(ctx, bucket, writeToken, accounts); err != nil { if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) { slog.Debug("[Scheduler] cache publish fenced", "bucket", bucket.String()) } else { @@ -269,7 +329,7 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, } } - return accounts, useMixed, nil + return accounts, nil } func (s *SchedulerSnapshotService) GetAccount(ctx context.Context, accountID int64) (*Account, error) { @@ -1614,6 +1674,15 @@ func (s *SchedulerSnapshotService) withFallbackTimeout(ctx context.Context) (con return context.WithTimeout(ctx, timeout) } +// withSharedFallbackTimeout 为合并回源设置时长上限:db_fallback_timeout_seconds 为正时取该值,否则取 schedulerSharedFallbackTimeout。 +func (s *SchedulerSnapshotService) withSharedFallbackTimeout(ctx context.Context) (context.Context, context.CancelFunc) { + timeout := schedulerSharedFallbackTimeout + if s.cfg != nil && s.cfg.Gateway.Scheduling.DbFallbackTimeoutSeconds > 0 { + timeout = time.Duration(s.cfg.Gateway.Scheduling.DbFallbackTimeoutSeconds) * time.Second + } + return context.WithTimeout(ctx, timeout) +} + func (s *SchedulerSnapshotService) isRunModeSimple() bool { return s.cfg != nil && s.cfg.RunMode == config.RunModeSimple } From cca745e8beefa08e1afa1312e64f7f04b98bcfce Mon Sep 17 00:00:00 2001 From: Daiyangcheng Date: Sun, 15 Nov 2026 21:17:48 +0800 Subject: [PATCH 80/85] fix(scheduler): keep openai_capabilities in the scheduler projection --- .../internal/repository/scheduler_cache.go | 5 ++ ...heduler_metadata_capabilities_unit_test.go | 53 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 backend/internal/repository/scheduler_metadata_capabilities_unit_test.go diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index f8a283d09f..aa7959c7bd 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1249,6 +1249,11 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any { // Candidate-list admission evaluates the account override before hydrating // the full account. Dropping it silently falls back to the platform threshold. keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", + // OpenAI 端点能力集必须进投影:候选过滤按 SupportsOpenAIEndpointCapability 判 + // capability_mismatch,而 Seedance 分支直接读该键、不走「未配置即放行」。 + // 裁掉后 Seedance 账号在选号阶段必然被剔除,表现为 /v1/models 能列出模型、 + // 建任务恒定 503 seedance_no_eligible_account。 + "openai_capabilities", // Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存: // 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛, // 不支持的账号要逐个选中后才被剔除。 diff --git a/backend/internal/repository/scheduler_metadata_capabilities_unit_test.go b/backend/internal/repository/scheduler_metadata_capabilities_unit_test.go new file mode 100644 index 0000000000..9d2580e23e --- /dev/null +++ b/backend/internal/repository/scheduler_metadata_capabilities_unit_test.go @@ -0,0 +1,53 @@ +//go:build unit + +package repository + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// buildSchedulerMetadataAccount 是调度候选的唯一投影出口,openAIAccountSkipReason +// 按 SupportsOpenAIEndpointCapability 判 capability_mismatch。Seedance 分支直接读 +// credentials.openai_capabilities 且不走「未配置即放行」,所以该键一旦被裁掉, +// Seedance 账号在选号阶段必然被剔除,而 /v1/models 走 DB 全量仍会列出模型。 +func TestSchedulerMetadataKeepsOpenAICapabilities(t *testing.T) { + account := service.Account{ + ID: 1, + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://relay.example.com/api/v3", + "openai_capabilities": []string{"seedance"}, + }, + } + + projected := buildSchedulerMetadataAccount(account) + + require.Equal(t, []string{"seedance"}, projected.Credentials["openai_capabilities"]) + require.Equal(t, "https://relay.example.com/api/v3", projected.Credentials["base_url"]) + require.True(t, projected.SupportsOpenAIEndpointCapability(service.OpenAIEndpointCapabilitySeedance)) +} + +func TestSchedulerMetadataDropsUnlistedCredentials(t *testing.T) { + account := service.Account{ + ID: 2, + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://relay.example.com/api/v3", + "openai_capabilities": []string{"seedance"}, + "model_mapping": map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"}, + "unlisted_secret": "drop-me", + }, + } + + projected := buildSchedulerMetadataAccount(account) + + require.Equal(t, map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"}, projected.Credentials["model_mapping"]) + require.NotContains(t, projected.Credentials, "unlisted_secret") +} From 5c96ee4d2941b484fe1960a8d57acaa739b62507 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Mon, 16 Nov 2026 05:53:22 +0800 Subject: [PATCH 81/85] fix(channels): persist Bedrock compatibility as a boolean --- frontend/src/views/admin/ChannelsView.vue | 16 +- .../ChannelsView.bedrockCompat.spec.ts | 177 ++++++++++++++++++ 2 files changed, 181 insertions(+), 12 deletions(-) create mode 100644 frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts diff --git a/frontend/src/views/admin/ChannelsView.vue b/frontend/src/views/admin/ChannelsView.vue index 5ee185131e..3633f27267 100644 --- a/frontend/src/views/admin/ChannelsView.vue +++ b/frontend/src/views/admin/ChannelsView.vue @@ -1196,18 +1196,10 @@ function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[ delete featuresConfig.codex_image_generation_bridge } - const bedrockCCCompat: Record = {} - for (const section of form.platforms) { - if (!section.enabled) continue - if (section.platform === 'anthropic') { - bedrockCCCompat[section.platform] = !!section.bedrock_cc_compat - } - } - if (Object.keys(bedrockCCCompat).length > 0) { - featuresConfig.bedrock_cc_compat = bedrockCCCompat - } else { - delete featuresConfig.bedrock_cc_compat - } + // The backend reads a channel-level boolean; send false explicitly to clear it on update. + featuresConfig.bedrock_cc_compat = form.platforms.some( + section => section.enabled && section.platform === 'anthropic' && section.bedrock_cc_compat + ) return { group_ids: uniqueGroupIds, model_pricing, model_mapping, features_config: featuresConfig } } diff --git a/frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts b/frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts new file mode 100644 index 0000000000..1291095480 --- /dev/null +++ b/frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts @@ -0,0 +1,177 @@ +import { defineComponent } from 'vue' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Channel, CreateChannelRequest, UpdateChannelRequest } from '@/api/admin/channels' +import ChannelsView from '@/views/admin/ChannelsView.vue' + +const { listChannels, createChannel, updateChannel, getGroups, showSuccess, showError } = vi.hoisted(() => ({ + listChannels: vi.fn(), + createChannel: vi.fn(), + updateChannel: vi.fn(), + getGroups: vi.fn(), + showSuccess: vi.fn(), + showError: vi.fn() +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + channels: { list: listChannels, create: createChannel, update: updateChannel }, + groups: { getAll: getGroups }, + settings: { getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false }) } + } +})) + +vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showSuccess, showError }) })) + +vi.mock('vue-i18n', async () => ({ + ...await vi.importActual('vue-i18n'), + useI18n: () => ({ t: (key: string) => key }) +})) + +function mountView() { + return mount(ChannelsView, { + global: { + stubs: { + AppLayout: defineComponent({ template: '
' }), + TablePageLayout: defineComponent({ + template: '
' + }), + BaseDialog: defineComponent({ + props: ['show'], + template: '
' + }), + DataTable: defineComponent({ + props: ['data'], + template: '
' + }), + Pagination: true, + ConfirmDialog: true, + EmptyState: true, + Select: true, + Icon: true, + PlatformIcon: true, + PricingEntryCard: true + } + } + }) +} + +type View = ReturnType + +async function clickButton(wrapper: View, text: string) { + const button = wrapper.findAll('button').find(button => button.text() === text) + expect(button).toBeDefined() + await button!.trigger('click') + await flushPromises() +} + +function platformCheckbox(wrapper: View, platform: string) { + return wrapper.findAll('label') + .find(label => label.text() === `admin.groups.platforms.${platform}`)! + .get('input[type="checkbox"]') +} + +function bedrockToggle(wrapper: View) { + return wrapper.findAll('[role="switch"]') + .find(toggle => toggle.element.parentElement?.textContent?.includes('admin.channels.form.bedrockCCCompat'))! +} + +function makeChannel(features: Record): Channel { + return { + id: 1, name: 'Bedrock relay', description: '', status: 'active', + billing_model_source: 'channel_mapped', restrict_models: false, + features_config: features, group_ids: [11, 22], model_pricing: [], model_mapping: {}, + apply_pricing_to_account_stats: false, account_stats_pricing_rules: [], + created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' + } +} + +describe('ChannelsView Bedrock compatibility', () => { + let stored: Channel[] + + beforeEach(() => { + vi.clearAllMocks() + localStorage.clear() + stored = [] + listChannels.mockImplementation(async () => ({ items: stored, total: stored.length })) + getGroups.mockResolvedValue([ + { id: 11, name: 'Anthropic group', platform: 'anthropic', rate_multiplier: 1 }, + { id: 22, name: 'OpenAI group', platform: 'openai', rate_multiplier: 1 } + ]) + createChannel.mockImplementation(async (request: CreateChannelRequest) => { + const channel = makeChannel(request.features_config || {}) + channel.group_ids = request.group_ids || [] + stored = [channel] + return channel + }) + updateChannel.mockImplementation(async (_id: number, request: UpdateChannelRequest) => { + stored = [{ ...stored[0], ...request } as Channel] + return stored[0] + }) + }) + + it.each([true, false])('creates and reopens a channel with compatibility %s', async enabled => { + const wrapper = mountView() + await flushPromises() + await clickButton(wrapper, 'admin.channels.createChannel') + await wrapper.get('input[required]').setValue('Bedrock relay') + await platformCheckbox(wrapper, 'anthropic').setValue(true) + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + await wrapper.findAll('label').find(label => label.text().includes('Anthropic group'))! + .get('input[type="checkbox"]').setValue(true) + if (enabled) await bedrockToggle(wrapper).trigger('click') + + await wrapper.get('#channel-form').trigger('submit') + await flushPromises() + expect(showError).not.toHaveBeenCalled() + expect(createChannel).toHaveBeenCalledOnce() + expect(createChannel.mock.calls[0][0].features_config.bedrock_cc_compat).toBe(enabled) + + await clickButton(wrapper, 'common.edit') + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + expect(bedrockToggle(wrapper).attributes('aria-checked')).toBe(String(enabled)) + wrapper.unmount() + }) + + it.each([true, false])('updates compatibility to %s while preserving other features', async enabled => { + stored = [makeChannel({ bedrock_cc_compat: true, future_feature: { enabled: true } })] + const wrapper = mountView() + await flushPromises() + await clickButton(wrapper, 'common.edit') + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + expect(bedrockToggle(wrapper).attributes('aria-checked')).toBe('true') + if (!enabled) await bedrockToggle(wrapper).trigger('click') + + await wrapper.get('#channel-form').trigger('submit') + await flushPromises() + expect(showError).not.toHaveBeenCalled() + expect(updateChannel).toHaveBeenCalledOnce() + expect(updateChannel.mock.calls[0][1].features_config).toMatchObject({ + bedrock_cc_compat: enabled, + future_feature: { enabled: true } + }) + + await clickButton(wrapper, 'common.edit') + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + expect(bedrockToggle(wrapper).attributes('aria-checked')).toBe(String(enabled)) + wrapper.unmount() + }) + + it('explicitly disables compatibility when the Anthropic section is removed', async () => { + stored = [makeChannel({ bedrock_cc_compat: true, future_feature: { enabled: true } })] + const wrapper = mountView() + await flushPromises() + await clickButton(wrapper, 'common.edit') + await platformCheckbox(wrapper, 'anthropic').setValue(false) + + await wrapper.get('#channel-form').trigger('submit') + await flushPromises() + expect(showError).not.toHaveBeenCalled() + expect(updateChannel).toHaveBeenCalledOnce() + expect(updateChannel.mock.calls[0][1]).toMatchObject({ + group_ids: [22], + features_config: { bedrock_cc_compat: false, future_feature: { enabled: true } } + }) + wrapper.unmount() + }) +}) From b46b3cbabcca6781a013a38140f151786334e930 Mon Sep 17 00:00:00 2001 From: shaw Date: Mon, 16 Nov 2026 17:03:29 +0800 Subject: [PATCH 82/85] test(handler): follow normalizeCodexUntrustedContext rename from #8769 #8769 renamed normalizeCodexPageContext to normalizeCodexUntrustedContext; the call-output gate test still referenced the old name, so go vet -tags unit failed once both changes were on main. --- backend/internal/handler/openai_codex_call_output_gate_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/handler/openai_codex_call_output_gate_test.go b/backend/internal/handler/openai_codex_call_output_gate_test.go index 3dbff2d493..6a7a7decb4 100644 --- a/backend/internal/handler/openai_codex_call_output_gate_test.go +++ b/backend/internal/handler/openai_codex_call_output_gate_test.go @@ -16,7 +16,7 @@ func TestCodexCallOutputGateSkipsDeclaredToolsWithoutCandidate(t *testing.T) { require.False(t, mayContainCodexCallOutputCandidate(body, "automation_update")) require.False(t, mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread")) for name, normalize := range map[string]func([]byte) ([]byte, bool){ - "page": normalizeCodexPageContext, + "untrusted": normalizeCodexUntrustedContext, "automation": normalizeCodexAutomationBootstrap, "delegation": normalizeCodexDelegationBootstrap, } { From 8d57f461ca85f89cef0bf94ae71acc01e35042ca Mon Sep 17 00:00:00 2001 From: shaw Date: Mon, 16 Nov 2026 17:04:52 +0800 Subject: [PATCH 83/85] fix(gemini): keep forced cache billing on sticky-session failover Keep the stable content session hash from this PR, but restore ForceCacheBilling on the native v1beta entry. Dropping it changed billing policy: a sticky session that failed over would be charged full input price instead of cache-read price. That also hit Antigravity accounts served by this handler, and made it inconsistent with /v1/messages, which still forces cache billing. Billing on this entry is now identical to main. --- backend/internal/handler/gemini_v1beta_handler.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 71e1af1371..2b54d71da6 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -816,11 +816,12 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { requestPayloadHash := service.HashUsageRequestPayload(body) inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) + // ForceCacheBilling 提前拍成标量,避免 worker 闭包保活 failover 状态里的响应体。 + forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) // 长上下文阶梯由目录数据驱动,统一在计费路径内生效,入口无需声明。 channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) - // 按上游实际返回的用量计费:粘性会话换号不做强制缓存计费,缓存读取只来自上游的 cachedContentTokenCount。 h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -835,6 +836,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { UserAgent: userAgent, IPAddress: clientIP, RequestPayloadHash: requestPayloadHash, + ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, SessionID: sessionID, ChannelUsageFields: channelUsageFields, From 2164ea48781731d3d129268d33c4220f55e6183b Mon Sep 17 00:00:00 2001 From: shaw Date: Mon, 16 Nov 2026 17:06:53 +0800 Subject: [PATCH 84/85] fix(billing): apply Vertex multi-region multiplier to default pricing only Group and channel prices are admin-configured final prices. The 1.1x multi-region factor now applies only when the token cost comes from default model pricing (LiteLLM/fallback). This matches account stats cost, which already applied the factor only at the model-file pricing tier. Adds a regression test for configured vs default pricing. --- .../internal/service/gateway_usage_billing.go | 18 +++++++--- .../service/gemini_cached_content_test.go | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 4522e5e958..232436bb81 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -1011,6 +1011,15 @@ func addCacheStorageToAccountStatsCost(usageLog *UsageLog, storageCost float64) usageLog.AccountStatsCost = &cost } +// upstreamPriceFactorApplies 判断上游端点价格倍数是否作用于本次 token 费用:只作用于默认模型价(LiteLLM/fallback)。 +// 管理员配置的分组价、渠道价视为最终价,不再叠加倍数,与账号统计成本只在默认价档位加价的口径一致。 +func (s *GatewayService) upstreamPriceFactorApplies(ctx context.Context, result *ForwardResult, apiKey *APIKey, billingModel string) bool { + if result.upstreamPriceFactor() == 1 { + return false + } + return s.resolveChannelPricing(ctx, billingModel, apiKey) == nil +} + // applyUpstreamPriceFactor 把上游端点价格倍数作用于按 token 计费的费用,按次等其他计费模式不受影响。 func applyUpstreamPriceFactor(cost *CostBreakdown, result *ForwardResult) { if cost == nil || (cost.BillingMode != "" && cost.BillingMode != string(BillingModeToken)) { @@ -1034,9 +1043,8 @@ func (s *GatewayService) calculateRecordUsageCost( if result.ImageCount > 0 { if !imageCountBillingApplies(apiKey, result.ImageEndpoint) { if resolved := s.resolveChannelPricing(ctx, billingModel, apiKey); resolved != nil && resolved.Mode == BillingModeToken { - tokenCost := s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) - applyUpstreamPriceFactor(tokenCost, result) - return tokenCost + // resolved 来自分组价或渠道价,是管理员配置的最终价,不叠加上游端点价格倍数。 + return s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) } } return s.calculateImageCost(ctx, result, apiKey, billingModel, imageMultiplier) @@ -1067,7 +1075,9 @@ func (s *GatewayService) calculateRecordUsageCost( tokenCost = &CostBreakdown{} } else { tokenCost = s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) - applyUpstreamPriceFactor(tokenCost, result) + if s.upstreamPriceFactorApplies(ctx, result, apiKey, billingModel) { + applyUpstreamPriceFactor(tokenCost, result) + } } if result.SearchCount > 0 { price := groupSearchPricePer1kFromAPIKey(apiKey) diff --git a/backend/internal/service/gemini_cached_content_test.go b/backend/internal/service/gemini_cached_content_test.go index 2a07968279..1a28a2a52e 100644 --- a/backend/internal/service/gemini_cached_content_test.go +++ b/backend/internal/service/gemini_cached_content_test.go @@ -436,6 +436,39 @@ func TestUpstreamPriceMultiplierScalesTokenCostOnly(t *testing.T) { require.InDelta(t, storage, storageOnly.TotalCost, 1e-12) } +// 管理员配置的分组价/渠道价是最终价,多区域端点倍数只作用于默认模型价。 +func TestUpstreamPriceMultiplierSkipsConfiguredPricing(t *testing.T) { + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(`{"gemini-3.7-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075, + "output_cost_per_token":0.00000375,"cache_read_input_token_cost":0.000000075}}`)) + require.NoError(t, err) + pricing.pricingData = data + billing := NewBillingService(&config.Config{}, pricing) + gateway := &GatewayService{billingService: billing, resolver: NewModelPricingResolver(nil, billing)} + + const ( + inputTokens = 10000 + outputTokens = 1000 + ) + usage := ClaudeUsage{InputTokens: inputTokens, OutputTokens: outputTokens} + groupInput, groupOutput := 0.000002, 0.000008 + groupID := int64(5) + configured := &APIKey{GroupID: &groupID, Group: &Group{ID: groupID, Hydrated: true, ModelPricing: []ChannelModelPricing{{ + Models: []string{"gemini-3.7-flash"}, BillingMode: BillingModeToken, InputPrice: &groupInput, OutputPrice: &groupOutput, + }}}} + cost := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", Usage: usage, UpstreamPriceMultiplier: 1.1, + }, configured, "gemini-3.7-flash", 1, 1, time.Now()) + require.InDelta(t, inputTokens*groupInput+outputTokens*groupOutput, cost.TotalCost, 1e-12) + + defaultGroupID := int64(6) + defaultPriced := &APIKey{GroupID: &defaultGroupID, Group: &Group{ID: defaultGroupID, Hydrated: true}} + cost = gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", Usage: usage, UpstreamPriceMultiplier: 1.1, + }, defaultPriced, "gemini-3.7-flash", 1, 1, time.Now()) + require.InDelta(t, (inputTokens*0.00000075+outputTokens*0.00000375)*1.1, cost.TotalCost, 1e-12) +} + func TestApplyUpstreamPriceFactorTokenModeOnly(t *testing.T) { result := &ForwardResult{UpstreamPriceMultiplier: 1.1} for mode, want := range map[string]float64{"": 1.1, string(BillingModeToken): 1.1, string(BillingModePerRequest): 1, string(BillingModeImage): 1} { From 32e70f3d4048ce5978dc15f72d5dd81f2e383a28 Mon Sep 17 00:00:00 2001 From: feeeei Date: Fri, 13 Nov 2026 10:50:31 +0800 Subject: [PATCH 85/85] =?UTF-8?q?feat(gemini):=20=E8=A1=A5=E9=BD=90=20Gemi?= =?UTF-8?q?ni=204=20Hydrogen=20=E8=AE=A1=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 内置兜底价:gemini-4-hydrogen 为 $1.50 输入 / $7.50 输出 / $0.075 缓存读取 (每百万 token),Priority 档为 1.8 倍;所有提示词长度同价 - 本地价格快照新增不带前缀的条目,含 Priority 档价格;只支持隐式缓存, 不带存储价 --- backend/internal/service/billing_service.go | 13 +++++ .../gemini_cache_storage_pricing_test.go | 4 +- .../internal/service/pricing_service_test.go | 49 +++++++++++++++++++ .../model_prices_and_context_window.json | 17 +++++++ 4 files changed, 82 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 37340fe652..8e526ec482 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -545,6 +545,16 @@ func (s *BillingService) initFallbackPricing() { SupportsCacheBreakdown: false, } + // Gemini 4 Hydrogen (Google AI pricing: $1.50 input / $7.50 output / + // $0.075 cached input per MTok; Priority is 1.8x). One rate covers every + // prompt length. + s.fallbackPrices["gemini-4-hydrogen"] = pricingWithPriorityMultiplier(&ModelPricing{ + InputPricePerToken: 1.5e-6, + OutputPricePerToken: 7.5e-6, + CacheReadPricePerToken: 0.075e-6, + SupportsCacheBreakdown: false, + }, 1.8) + // OpenAI GPT-5.4(业务指定价格) s.fallbackPrices["gpt-5.4"] = &ModelPricing{ InputPricePerToken: 2.5e-6, // $2.5 per MTok @@ -1153,6 +1163,9 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { if strings.Contains(modelLower, "gemini-4-argon") { return s.fallbackPrices["gemini-4-argon"] } + if strings.Contains(modelLower, "gemini-4-hydrogen") { + return s.fallbackPrices["gemini-4-hydrogen"] + } // DeepSeek 系列:官方模型 V4 Pro/Flash(含 vision-exp)按各自价卡; // 其余 deepseek-*(含已停服的 deepseek-chat / deepseek-reasoner 与未知型号) diff --git a/backend/internal/service/gemini_cache_storage_pricing_test.go b/backend/internal/service/gemini_cache_storage_pricing_test.go index 97a8aef6a2..49cddb5087 100644 --- a/backend/internal/service/gemini_cache_storage_pricing_test.go +++ b/backend/internal/service/gemini_cache_storage_pricing_test.go @@ -43,10 +43,12 @@ func TestBuiltinGeminiCacheStoragePrice(t *testing.T) { {"gemini-flash-latest", 1e-6}, {"gemini-flash-lite-latest", 1e-6}, {"gemini-pro-latest", 4.5e-6}, - // 无存储价(Gemini 4 Argon 仅支持隐式缓存) + // 无存储价(Gemini 4 Argon / Hydrogen 仅支持隐式缓存) {"gemini-4-argon", 0}, {"gemini-4-argon-high", 0}, {"gemini-4-argon-cyber-permissive", 0}, + {"gemini-4-hydrogen", 0}, + {"models/gemini-4-hydrogen", 0}, {"gemini-embedding-001", 0}, {"gemini-unknown-model", 0}, {"claude-sonnet-5-5", 0}, diff --git a/backend/internal/service/pricing_service_test.go b/backend/internal/service/pricing_service_test.go index d72e2f1214..42570746ec 100644 --- a/backend/internal/service/pricing_service_test.go +++ b/backend/internal/service/pricing_service_test.go @@ -819,6 +819,55 @@ func TestDefaultPricingIncludesGemini4ArgonRates(t *testing.T) { require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-argon") } +func TestBillingService_Gemini4HydrogenFallbackIsBillable(t *testing.T) { + svc := NewBillingService(&config.Config{}, nil) + tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000} + + for _, tc := range []struct { + model string + serviceTier string + input, output, read float64 + }{ + {"gemini-4-hydrogen", "", 1.5, 7.5, 0.075}, + {"models/gemini-4-hydrogen", "", 1.5, 7.5, 0.075}, + {"projects/p/locations/global/publishers/google/models/gemini-4-hydrogen", "", 1.5, 7.5, 0.075}, + {"gemini-4-hydrogen", "priority", 2.7, 13.5, 0.135}, + } { + t.Run(tc.model+"/"+tc.serviceTier, func(t *testing.T) { + cost, err := svc.CalculateCostWithServiceTier(tc.model, tokens, 1, tc.serviceTier) + require.NoError(t, err) + require.InDelta(t, tc.input, cost.InputCost, 1e-12) + require.InDelta(t, tc.output, cost.OutputCost, 1e-12) + require.InDelta(t, tc.read, cost.CacheReadCost, 1e-12) + require.InDelta(t, tc.input+tc.output+tc.read, cost.TotalCost, 1e-12) + }) + } +} + +func TestDefaultPricingIncludesGemini4HydrogenRates(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json")) + require.NoError(t, err) + + pricingSvc := &PricingService{} + pricingData, err := pricingSvc.parsePricingData(data) + require.NoError(t, err) + pricingSvc.pricingData = pricingData + + pricing := pricingSvc.GetModelPricing("gemini-4-hydrogen") + require.NotNil(t, pricing) + require.Equal(t, "gemini", pricing.LiteLLMProvider) + require.InDelta(t, 1.5e-6, pricing.InputCostPerToken, 1e-15) + require.InDelta(t, 7.5e-6, pricing.OutputCostPerToken, 1e-15) + require.InDelta(t, 0.075e-6, pricing.CacheReadInputTokenCost, 1e-15) + // Priority 档为标准价的 1.8 倍;单一价档不分提示词长度,显式缓存不可用故无存储价。 + require.InDelta(t, 2.7e-6, pricing.InputCostPerTokenPriority, 1e-15) + require.InDelta(t, 13.5e-6, pricing.OutputCostPerTokenPriority, 1e-15) + require.InDelta(t, 0.135e-6, pricing.CacheReadInputTokenCostPriority, 1e-15) + require.Zero(t, pricing.LongContextInputTokenThreshold) + require.Zero(t, pricing.CacheStorageCostPerTokenPerHour) + require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-hydrogen") +} + func TestDefaultPricingIncludesGrok47FastRates(t *testing.T) { data, err := os.ReadFile(filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json")) require.NoError(t, err) diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json index 0f48dc14f7..733cc09954 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -2777,6 +2777,23 @@ "supports_reasoning": true, "supports_service_tier": true }, + "gemini-4-hydrogen": { + "cache_read_input_token_cost": 7.5e-08, + "cache_read_input_token_cost_priority": 1.35e-07, + "input_cost_per_token": 1.5e-06, + "input_cost_per_token_priority": 2.7e-06, + "litellm_provider": "gemini", + "max_input_tokens": 1048576, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 7.5e-06, + "output_cost_per_token_priority": 1.35e-05, + "source": "https://aistudio.google.com/docs/pricing#gemini-4-hydrogen", + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_service_tier": true + }, "gemini-embedding-001": { "input_cost_per_token": 1.5e-07, "litellm_provider": "vertex_ai-embedding-models",