Merge pull request #9205 from fengshao1227/fix/openai-manual-reset-earliest-credit

fix(openai): spend the earliest-expiring reset credit on manual reset
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-12-02 12:06:06 +08:00
commit 4c953d9252
4 files changed
+155 -3

No files matched your search

@@ -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)
}
@@ -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"])
})
}
}
@@ -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().
@@ -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 {