Files
magpie/internal/usage/window_holds_history_test.go
T
yetoneandNorethSea b00da3860c usage: a past cycle shows its own whole-window estimate, and a reset ends a dry run (#2009, #2010, NorethSea)
Ported from NorethSea's fork (abed2e224) and re-derived on main.

What it does:
- A known reset ends a dry run (a stretch where a window read 0% left), even
  when the next poll sees the refill later. A stale dry reading taken after
  its own reset no longer extends the run. Calls from the reset on are not
  treated as "maybe paid from credits".
- A refill observed later than reset minus span
  (QuotaPoint.StartsCycleAfter, the boundaries history sampling keeps)
  starts what is reckoned. Calls before a fixed-deadline refill stay in the
  cycle before it. A first reading is not a reset.
- Picking a past cycle in Usage > Allowances > Trends > Cycle asks
  GET /api/usage/quotas/history/holds once per selection
  (quotaCycleHoldsOf). The route asks no vendor. HistoricalWindowHolds
  reckons each window at its own last reading in the cycle, using the
  ledger and readings from before that reading. "Loading..." shows while it
  is pending. An answer for a cycle no longer picked is dropped. The card's
  Refresh, or an asked read, reckons again. The estimate's tooltip names the
  window's start and the reading's time.

Changed from the fork:
- After a run closed at its reset, the fork reset lastLeft to zero. A
  window that ran dry again before its next reset then opened a run from
  time zero, which hid every window's estimate, the weekly one included.
  The next run now starts no earlier than that reset.
  TestWindowHoldsDryAgainAfterReset covers it (red with the fork's line).
- The fork narrowed the live card's Span to the observed refill. Span also
  feeds provider.WithWindowStarts, so the window's Pace would have moved.
  withSpansOf puts the card's spans back after reckoning. A span assertion
  in TestWindowHoldsUsesObservedRefillStart covers it (red without it).
- The fork's historical snapshot dropped the card's Balance. That slipped
  past the gate a live card has (holdsBounds), so a card that tells a
  balance got past-cycle estimates. Balance is now kept. Covered in
  TestHistoricalWindowHoldsUsesEachWindowsOwnReading (red without it). The
  fork's fixture had a Codex card with a Balance, which no Codex card has.
- Main has since added HoldsWhy (#2045). The fork's own "Whole: not enough
  reliable data" line and its .quota-holds-unknown CSS are left out. A past
  cycle uses main's holdsUnknownLine and its reasons, as a live card does.
  A window with neither an estimate nor a reason shows nothing, where the
  fork showed its unknown line.
- withRecordedWindowStarts is ported to main's holdsBounds(start, end, why).
- quota-refresh-order.test.cjs's VM harness now stubs quotaCycleHolds,
  which loadQuotas and quotaRefresh clear.

Left out: nothing else from the fork. Past prices aren't kept, so a past
cycle's cost uses today's API list prices (documented). Credits can't be
attributed per call, so none is attempted (documented).

What was run:
- gofmt -l: clean. go vet -tags nogui ./... for GOOS darwin, linux and windows.
- go test -tags nogui ./internal/usage ./internal/gui ./internal/provider:
  ok.
- Each of the three fixes above was reverted by hand, and its test went red.
- GUI, Chromium and WebKit:
  - quota-curve: 30/30. Also run at 1100 and 420 wide: 60/60 (all five
    languages).
  - Also: quota-*, i18n-keys, gui-de/ja/zh-tw, usage-card-refresh,
    usage-refresh*, usage-stale-answer, usage-remote-cards,
    usage-accounts*, usage-quota-head, usage-pack and usage-alert.
  - Reds: quota-count-wrap and quota-name-translated are red in WebKit,
    the same as on origin/main 707fbb249. Filed as #2228.
  - The GUI break-check (main's !sub.history gate put back) turns the new
    quota-curve test red.
- Full suite: SUITE_LINE

Co-authored-by: NorethSea <963979204@qq.com>
2026-10-15 23:08:00 +08:00

129 lines
5.8 KiB
Go

package usage
import (
"encoding/json"
"github.com/yetone/magpie/internal/provider"
"testing"
"time"
)
func TestHistoricalWindowHoldsUsesEachWindowsOwnReading(t *testing.T) {
holdsHome(t)
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
from, to := now.Add(-13*24*time.Hour), now.Add(-6*24*time.Hour)
weekAt := to.Add(-24 * time.Hour)
fiveReset := to.Add(-time.Hour)
fiveStart := fiveReset.Add(-5 * time.Hour)
fiveAt := to.Add(-2 * time.Hour)
futureReset := now.Add(24 * time.Hour)
call := func(at time.Time, n int, user string) {
Append(Record{Time: at, Provider: "codex", ProviderAccount: user, Model: "gpt-5.5", Input: n, Status: 200})
}
user := "sample@example.com"
call(from.Add(-time.Hour), 1, user) // the ledger covers the entire old week
call(weekAt.Add(-time.Hour), 1100, user)
call(fiveAt.Add(-time.Hour), 2200, user)
call(fiveAt.Add(time.Minute), 999999, user) // after both selected readings
call(now.Add(-time.Hour), 888888, user) // today's traffic
call(fiveAt.Add(-time.Minute), 777777, "other@example.com")
hist := []provider.QuotaHistory{{Provider: "codex", User: user, Lines: []provider.QuotaLine{
{Name: "5 hours", Points: []provider.QuotaPoint{{At: fiveAt, Left: 80, Start: &fiveStart, ResetsAt: &fiveReset}, {At: now, Left: 0, ResetsAt: &futureReset}}},
{Name: "7 days", Points: []provider.QuotaPoint{{At: weekAt, Left: 60, Start: &from, ResetsAt: &to}, {At: now, Left: 0, ResetsAt: &futureReset}}},
}}}
// Today's percentages are not historical observations.
cards := []provider.SubscriptionQuota{{Provider: "codex", User: user, Windows: []provider.QuotaWindow{
{Name: "5 hours", Used: 1, ResetsAt: &futureReset, Holds: &provider.WindowHolds{Tokens: 9999999}},
{Name: "7 days", Used: 1, ResetsAt: &futureReset},
}}}
got := HistoricalWindowHolds(cards, hist, from, to)
if len(got) != 2 {
t.Fatalf("historical windows: %+v", got)
}
for i, want := range []struct {
at time.Time
tokens int64
used float64
}{{fiveAt, 11000, 20}, {weekAt, 2750, 40}} {
w := got[i].Windows[0]
if h := w.Holds; h == nil || h.Tokens != want.tokens || h.Used != want.used || !h.Priced || !got[i].ReadAt.Equal(want.at) {
t.Errorf("%s: %+v at %v, want %d at %v", w.Name, h, got[i].ReadAt, want.tokens, want.at)
}
}
if cards[0].Windows[0].Holds.Tokens != 9999999 || hist[0].Lines[0].Points[0].Left != 80 {
t.Fatal("the caller's current card or history was changed")
}
// A range with no readings never falls back to the current card.
if got := HistoricalWindowHolds(cards, hist, to, now.Add(-time.Hour)); len(got) != 0 {
t.Fatalf("missing old readings: %+v", got)
}
// A card that tells a balance may have paid from it, so a past cycle
// is no more reckoned than the live one.
paid := []provider.SubscriptionQuota{{Provider: "codex", User: user, Balance: "12 credits", Windows: cards[0].Windows}}
for _, s := range HistoricalWindowHolds(paid, hist, from, to) {
if w := s.Windows[0]; w.Holds != nil || w.HoldsWhy != "" {
t.Errorf("%s with a balance: %+v (%q)", w.Name, w.Holds, w.HoldsWhy)
}
}
}
func TestWindowHoldsUsesObservedRefillStart(t *testing.T) {
holdsHome(t)
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
reset := now.Add(3 * 24 * time.Hour)
nominal := reset.Add(-7 * 24 * time.Hour)
refill := now.Add(-24 * time.Hour)
before := refill.Add(-time.Hour)
at := now.Add(-time.Hour)
user := "sample@example.com"
points := []provider.QuotaPoint{{At: before, Left: 20, Start: &nominal, ResetsAt: &reset}, {At: refill, Left: 100, Start: &nominal, ResetsAt: &reset}, {At: at, Left: 80, Start: &nominal, ResetsAt: &reset}}
hist := []provider.QuotaHistory{{Provider: "codex", User: user, Lines: []provider.QuotaLine{{Name: "7 days", Points: points}}}}
b, _ := json.Marshal(map[string]map[string][]provider.QuotaPoint{"codex|" + user: {"7 days": points}})
if err := provider.MergeQuotaHistory(b, now); err != nil {
t.Fatal(err)
}
for _, r := range []Record{
{Time: nominal.Add(-time.Hour), Input: 1},
{Time: before, Input: 9000000},
{Time: refill.Add(time.Hour), Input: 1000},
} {
r.Provider = "codex"
r.ProviderAccount = user
r.Model = "gpt-5.5"
r.Status = 200
Append(r)
}
cards := []provider.SubscriptionQuota{{Provider: "codex", User: user, ReadAt: &at, Windows: []provider.QuotaWindow{{Name: "7 days", Used: 20, ResetsAt: &reset, Span: 7 * 24 * time.Hour}}}}
for name, got := range map[string][]provider.SubscriptionQuota{
"current": WithWindowHolds(cards, now),
"historical": HistoricalWindowHolds(cards, hist, refill, now),
} {
if len(got) != 1 {
t.Fatalf("%s: %+v", name, got)
}
h := got[0].Windows[0].Holds
if h == nil || h.Tokens != 5000 || !h.Since.Equal(refill) {
t.Errorf("%s: %+v, want 5000 tokens since %v", name, h, refill)
}
}
// The observed start narrows only what is reckoned: the card's window
// keeps its span, so its Pace (WithWindowStarts) is the vendor's.
if got := WithWindowHolds(cards, now)[0].Windows[0]; got.Span != 7*24*time.Hour {
t.Fatalf("current window's span became %v", got.Span)
}
if cards[0].Windows[0].Span != 7*24*time.Hour {
t.Fatal("cached window changed")
}
}
func TestWindowHoldsFirstReadingIsNotARefill(t *testing.T) {
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
at, reset := now.Add(-time.Hour), now.Add(3*24*time.Hour)
cards := []provider.SubscriptionQuota{{Provider: "codex", User: "sample", ReadAt: &at, Windows: []provider.QuotaWindow{{Name: "7 days", Used: 20, ResetsAt: &reset, Span: 7 * 24 * time.Hour}}}}
firstAt := at.Add(-time.Hour)
hist := []provider.QuotaHistory{{Provider: "codex", User: "sample", Lines: []provider.QuotaLine{{Name: "7 days", Points: []provider.QuotaPoint{{At: firstAt, Left: 80, ResetsAt: &reset}}}}}}
got := withRecordedWindowStarts(cards, hist, now)
if got[0].Windows[0].Span != 7*24*time.Hour {
t.Fatal("first observed reading was mistaken for a reset")
}
}