Merge pull request #8698 from r266-tech/codex/anthropic-quota-window-start

fix(usage): advance five-hour window start on active quota sync
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-11-16 16:30:11 +08:00
commit 2df3dbcfbb
2 files changed
+31

No files matched your search

@@ -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 {
@@ -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() {