From 7613baf97c310ca676af5e06c62cf11e33720232 Mon Sep 17 00:00:00 2001 From: li Date: Wed, 2 Dec 2026 10:19:35 +0800 Subject: [PATCH] fix(openai): spend the earliest-expiring reset credit on manual reset The automatic reset sorts the available credits by expiry and consumes the first one by id, but the admin reset button sent no credit_id and let upstream pick. Upstream can then spend a later credit and leave the one closest to expiry to lapse, while the account list shows that earliest expiry next to the button. ResetCredit now reads the credit list first and targets the credit that expires first. When the list cannot name it (request failed, a credit without expiry or id, fewer credits listed than available, unparsable expiry) the request stays untargeted as before. --- .../service/openai_quota_manual_reset.go | 40 ++++++++ .../service/openai_quota_manual_reset_test.go | 98 +++++++++++++++++++ .../internal/service/openai_quota_service.go | 12 ++- .../service/openai_quota_spark_window_test.go | 8 ++ 4 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/openai_quota_manual_reset.go create mode 100644 backend/internal/service/openai_quota_manual_reset_test.go diff --git a/backend/internal/service/openai_quota_manual_reset.go b/backend/internal/service/openai_quota_manual_reset.go new file mode 100644 index 0000000000..a85f65fbe1 --- /dev/null +++ b/backend/internal/service/openai_quota_manual_reset.go @@ -0,0 +1,40 @@ +package service + +import ( + "strings" + "time" +) + +// earliestOpenAIResetCreditID picks the credit a manual reset consumes: the +// available codex_rate_limits credit that expires first, the same order the +// automatic reset follows (selectOpenAIAutoResetCandidate). A consume request +// without credit_id lets upstream choose, which can spend a later credit and +// leave the one closest to expiry to lapse. +// +// It returns "" whenever the details cannot name that credit with certainty +// (query failed, an available credit has no expiry or id, an expiry does not +// parse), and the caller then keeps the untargeted request. +func earliestOpenAIResetCreditID(details *openAIRateLimitResetCreditDetails) string { + if details == nil || len(details.AutoResetCandidates) == 0 { + return "" + } + candidates := details.AutoResetCandidates + if len(candidates) < details.AvailableCreditCount { + return "" + } + if details.AvailableCount != nil && len(candidates) < *details.AvailableCount { + return "" + } + earliest := -1 + var earliestAt time.Time + for i, candidate := range candidates { + expiresAt, err := time.Parse(time.RFC3339, candidate.ExpiresAt) + if err != nil { + return "" + } + if earliest < 0 || expiresAt.Before(earliestAt) { + earliest, earliestAt = i, expiresAt + } + } + return strings.TrimSpace(candidates[earliest].ID) +} diff --git a/backend/internal/service/openai_quota_manual_reset_test.go b/backend/internal/service/openai_quota_manual_reset_test.go new file mode 100644 index 0000000000..aaa727a5bc --- /dev/null +++ b/backend/internal/service/openai_quota_manual_reset_test.go @@ -0,0 +1,98 @@ +package service + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +const ( + manualResetCreditsPath = "/backend-api/wham/rate-limit-reset-credits" + manualResetConsumePath = "/backend-api/wham/rate-limit-reset-credits/consume" +) + +type manualResetUpstream struct { + paths []string + consumeBody map[string]string +} + +// runManualReset serves creditsStatus/creditsBody on the credit list endpoint, +// accepts the consume call, and runs the admin (untargeted) ResetCredit. +func runManualReset(t *testing.T, accountID int64, creditsStatus int, creditsBody string) *manualResetUpstream { + t.Helper() + account := &Account{ + ID: accountID, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"chatgpt_account_id": "account-manual-reset"}, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + tokenCache := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(account): "fake-token"}} + upstream := &manualResetUpstream{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstream.paths = append(upstream.paths, r.Method+" "+r.URL.Path) + w.Header().Set("content-type", "application/json") + switch r.URL.Path { + case manualResetCreditsPath: + w.WriteHeader(creditsStatus) + _, _ = w.Write([]byte(creditsBody)) + case manualResetConsumePath: + require.NoError(t, json.NewDecoder(r.Body).Decode(&upstream.consumeBody)) + _, _ = w.Write([]byte(`{"code":"ok","windows_reset":1}`)) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + + svc := NewOpenAIQuotaService(repo, nil, NewOpenAITokenProvider(repo, tokenCache, nil), newQuotaRedirectingFactory(srv), nil) + result, err := svc.ResetCredit(context.Background(), account.ID) + require.NoError(t, err) + require.Equal(t, "ok", result.Code) + return upstream +} + +func TestResetCreditConsumesEarliestExpiringCredit(t *testing.T) { + // Listed out of order, with a spent credit that expires even earlier. + upstream := runManualReset(t, 230, http.StatusOK, `{"available_count":3,"credits":[ + {"id":"credit-dec-26","expires_at":"2026-12-26T00:00:00Z","status":"available"}, + {"id":"credit-spent","expires_at":"2026-12-01T00:00:00Z","status":"used"}, + {"id":"credit-dec-03","expires_at":"2026-12-03T00:00:00Z","status":"available"}, + {"id":"credit-dec-13","expires_at":"2026-12-13T00:00:00Z","status":"available"}]}`) + + require.Equal(t, []string{"GET " + manualResetCreditsPath, "POST " + manualResetConsumePath}, upstream.paths) + require.Equal(t, "credit-dec-03", upstream.consumeBody["credit_id"]) + require.NotEmpty(t, upstream.consumeBody["redeem_request_id"]) +} + +func TestResetCreditLetsUpstreamChooseWhenEarliestCreditIsUnknown(t *testing.T) { + cases := []struct { + name string + status int + body string + }{ + {"credit list unavailable", http.StatusInternalServerError, `{"error":"boom"}`}, + {"earliest credit has no id", http.StatusOK, `{"credits":[ + {"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"}, + {"expires_at":"2026-12-03T00:00:00Z"}]}`}, + {"an available credit has no expiry", http.StatusOK, `{"credits":[ + {"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"}, + {"id":"credit-unknown"}]}`}, + {"fewer credits listed than available", http.StatusOK, `{"available_count":2,"credits":[ + {"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"}]}`}, + {"expiry does not parse", http.StatusOK, `{"credits":[ + {"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"}, + {"id":"credit-odd","expires_at":"next week"}]}`}, + } + for i, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + upstream := runManualReset(t, int64(240+i), tc.status, tc.body) + + require.Equal(t, []string{"GET " + manualResetCreditsPath, "POST " + manualResetConsumePath}, upstream.paths) + require.NotContains(t, upstream.consumeBody, "credit_id") + require.NotEmpty(t, upstream.consumeBody["redeem_request_id"]) + }) + } +} diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 5fd986a18c..ea3836ef54 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -346,8 +346,10 @@ func (s *OpenAIQuotaService) queryResetCreditDetails(ctx context.Context, client } // ResetCredit consumes one rate_limit_reset_credit for the given OpenAI account. -// The redeem_request_id is auto-generated (uuid-like) — upstream uses it for -// idempotency. Returns the consumed credit metadata so the UI can refresh. +// It targets the credit that expires first when the credit details name it, +// and otherwise lets upstream choose. The redeem_request_id is auto-generated +// (uuid-like) — upstream uses it for idempotency. Returns the consumed credit +// metadata so the UI can refresh. func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) (*OpenAIQuotaResetResult, error) { redeemRequestID, err := generateRedeemRequestID() if err != nil { @@ -403,6 +405,10 @@ func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, c callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() agentIdentity := s.isAgentIdentityAccount(ctx, accountID) + if !targeted { + // A manual reset spends the credit that expires first, like the automatic reset. + creditID = earliestOpenAIResetCreditID(s.queryResetCreditDetails(callCtx, client, accessToken, chatGPTAccountID, fedRAMP, accountID)) + } var payload OpenAIQuotaResetResult for recovered := false; ; { @@ -412,7 +418,7 @@ func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, c } headers["content-type"] = "application/json" body := map[string]string{"redeem_request_id": redeemRequestID} - if targeted { + if creditID != "" { body["credit_id"] = creditID } resp, err := client.R(). diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index 8bda444bf9..59d5287fc7 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -245,6 +245,10 @@ func TestResetCreditAgentIdentityUsesAssertionAndRecoversInvalidTaskOnce(t *test _, _ = w.Write([]byte(`{"task_id":"task-reset-new"}`)) return } + if r.URL.Path == "/backend-api/wham/rate-limit-reset-credits" { + http.NotFound(w, r) // no credit details: the reset stays untargeted + return + } resetCalls++ assertions = append(assertions, r.Header.Get("authorization")) require.Equal(t, "account-reset-recovery", r.Header.Get("chatgpt-account-id")) @@ -306,6 +310,10 @@ func TestResetCreditAgentIdentityReusesConcurrentlyRecoveredTask(t *testing.T) { _, _ = w.Write([]byte(`{"task_id":"task-reset-unexpected"}`)) return } + if r.URL.Path == "/backend-api/wham/rate-limit-reset-credits" { + http.NotFound(w, r) // no credit details: the reset stays untargeted + return + } resetCalls++ assertions = append(assertions, r.Header.Get("authorization")) if resetCalls == 1 {