Files
magpie/internal/usage/window_holds.go
T
yetone e10b7f92a1 usage: a window whose calls may have been paid from credits shows no whole (#2010, NorethSea)
Once a Codex account's window read 100% used, ChatGPT kept answering its
calls from credits; once the credits ran out the card had no Balance, so
holdsBounds let the whole-window estimate back in and counted those calls
as the subscription's. The reporter's fixture (5 hours at 100%, week at
50%, a 100k subscription call and a 900k credits call) gave routed
1000000 / whole 2000000 for the week. Claude's extra usage after a dry
window is the same case.

dryRuns builds each account's dry runs from its kept quota history plus
the card's own reading: from the last reading with some left (unknown =
zero) through the first reading of none, to the first with some again.
A window that counted a call in a run is not reckoned when the vendor
answered a call after the run's first dry reading, or when no earlier
reading with some left is known. A run where everything after the dry
reading was turned away (no credits) leaves the estimate as it was, and
a run before the window began doesn't touch it.

Run: go test -tags nogui ./internal/usage ./internal/gui (HOME sandbox),
gofmt, GOOS=linux/windows go vet. TestWindowHoldsLeavesOutCallsPaidOtherwise
goes red with the exclusion disabled (prints the reporter's 1000000 /
2000000) and with the "answered after the dry reading" condition dropped.
Not tried against a real account that spent credits.
2026-10-14 04:32:01 +08:00

265 lines
8.7 KiB
Go

package usage
// What a whole subscription window holds (Chiao on Discord): the Usage
// page's account cards show each window's share used, as the vendor reads
// it; magpie knows what it routed through the account since the window
// began, so the whole is about that over the share. It is told only where
// that is honest: the window's start and the account's calls are known,
// magpie's log reaches back to the start, and enough of it is used for a
// rounded percent to scale up (provider.HoldsFloor).
import (
"math"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// WithWindowHolds is qs with each window's Holds reckoned from the log, as
// it stood at now. qs itself, which the caller may share, is left as it is.
func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota {
since, ok := holdsSince(qs, now)
if !ok {
return qs
}
s := readLogSnapshot()
dry := dryRuns(qs, provider.QuotaHistories(since, "", ""), now)
return windowHolds(qs, now, s.firstOwn, apiPricer(), provider.Renamed(), dry, func(fn func(Record)) { s.visit(since, fn) })
}
// holdsSince is the earliest start of a window that could be reckoned.
func holdsSince(qs []provider.SubscriptionQuota, now time.Time) (time.Time, bool) {
var since time.Time
found := false
for _, q := range qs {
at := readAtOf(q, now)
for _, w := range q.Windows {
if start, _, ok := holdsBounds(q, w, at); ok && (!found || start.Before(since)) {
since, found = start, true
}
}
}
return since, found
}
func readAtOf(q provider.SubscriptionQuota, now time.Time) time.Time {
if q.ReadAt != nil && !q.ReadAt.After(now) {
return *q.ReadAt
}
return now
}
// holdsBounds is the window of q's account to reckon w's whole over, ok
// only where w can be: an account's own card, a window that runs out and
// starts again on a known clock, counts a whole account's or some named
// models' calls, and is used enough, and a reading not past its reset.
func holdsBounds(q provider.SubscriptionQuota, w provider.QuotaWindow, at time.Time) (time.Time, time.Time, bool) {
if q.Error != "" || q.From != "" || q.User == "" || q.Balance != "" {
return time.Time{}, time.Time{}, false
}
if w.Unlimited || w.Aside || w.Family != "" || w.Pool != "" || math.IsNaN(w.Used) || w.Used < provider.HoldsFloor {
return time.Time{}, time.Time{}, false
}
start, end, ok := w.Bounds(at)
if !ok || !end.After(at) || !start.Before(at) {
return time.Time{}, time.Time{}, false
}
return start, end, true
}
// dryRun is a stretch in which one of an account's windows had nothing
// left (#2010, NorethSea): from the last reading that still had some (zero
// when none is known) through the first that read none, to the first that
// had some again (zero while none has). A call the vendor answered in it
// may have been paid from credits (Codex) or extra usage (Claude), not
// from the windows, and nothing in the log tells which.
type dryRun struct{ lastLeft, firstDry, refilled time.Time }
func (d dryRun) holds(t time.Time) bool {
return !t.Before(d.lastLeft) && (d.refilled.IsZero() || t.Before(d.refilled))
}
// dryRuns is each account's dry runs, by provider and lowercased user,
// from its windows' kept readings and the card's own reading of them.
func dryRuns(qs []provider.SubscriptionQuota, hist []provider.QuotaHistory, now time.Time) map[string][]dryRun {
out := map[string][]dryRun{}
lines := map[string][]provider.QuotaPoint{} // account and window → readings, oldest first
for _, h := range hist {
for _, l := range h.Lines {
lines[h.Provider+"\x00"+strings.ToLower(h.User)+"\x00"+l.Name] = l.Points
}
}
for _, q := range qs {
if q.User == "" {
continue
}
at := readAtOf(q, now)
for _, w := range q.Windows {
if w.Unlimited || w.Aside || w.Family != "" || math.IsNaN(w.Used) {
continue
}
k := q.Provider + "\x00" + strings.ToLower(q.User) + "\x00" + w.Name
pts := lines[k]
if n := len(pts); n == 0 || pts[n-1].At.Before(at) {
pts = append(append([]provider.QuotaPoint(nil), pts...), provider.QuotaPoint{At: at, Left: max(0, 100-w.Used)})
}
lines[k] = pts
}
}
for k, pts := range lines {
acct := k[:strings.LastIndex(k, "\x00")]
var run *dryRun
var lastLeft time.Time
for _, p := range pts {
switch {
case p.Left > 0 && run != nil:
run.refilled = p.At
out[acct] = append(out[acct], *run)
run, lastLeft = nil, p.At
case p.Left > 0:
lastLeft = p.At
case run == nil:
run = &dryRun{lastLeft: lastLeft, firstDry: p.At}
}
}
if run != nil {
out[acct] = append(out[acct], *run)
}
}
return out
}
// windowHolds fills in each window's Holds from the calls read gives: the
// calls of the card's provider (by the id it has now) answered by its
// account, to a model the window counts, from the window's start to when
// its share was read. first is the log's first call: a window begun before
// it has calls magpie can't see, and isn't reckoned. Nor is a window with a
// call in one of its account's dry runs that may have been paid otherwise:
// one where the vendor answered a call after a reading of none left, or
// where no reading with some left is known before it.
func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf func(Record) *catalog.Price, renamed map[string]string, dry map[string][]dryRun, read func(func(Record))) []provider.SubscriptionQuota {
type slot struct{ q, w int }
type span struct{ start, end time.Time }
want := map[slot]span{}
byAccount := map[string][]slot{}
for i, q := range qs {
at := readAtOf(q, now)
for j, w := range q.Windows {
start, _, ok := holdsBounds(q, w, at)
if !ok || first.IsZero() || first.After(start) {
continue
}
k := q.Provider + "\x00" + strings.ToLower(q.User)
byAccount[k] = append(byAccount[k], slot{i, j})
want[slot{i, j}] = span{start, at}
}
}
if len(want) == 0 {
return qs
}
sums := map[slot]*provider.WindowHolds{}
unpriced := map[slot]bool{}
type runKey struct {
account string
run int
}
paidOtherwise := map[runKey]bool{} // the vendor answered a call after a reading of none left
inRun := map[slot][]runKey{} // the dry runs a counted call fell in
read(func(r Record) {
if r.IsRejected() || r.IsReported() || r.Input+r.Output == 0 {
return
}
if next, ok := renamed[r.Provider]; ok {
r.Provider = next
}
acct := r.Provider + "\x00" + strings.ToLower(r.Account())
var runs []runKey
for i, d := range dry[acct] {
if !d.holds(r.Time) {
continue
}
k := runKey{acct, i}
runs = append(runs, k)
if d.lastLeft.IsZero() || r.Status < 400 && !r.Time.Before(d.firstDry) {
paidOtherwise[k] = true
}
}
for _, s := range byAccount[acct] {
b := want[s]
if r.Time.Before(b.start) || r.Time.After(b.end) || !qs[s.q].Windows[s.w].Counts(r.Model) {
continue
}
inRun[s] = append(inRun[s], runs...)
h := sums[s]
if h == nil {
h = &provider.WindowHolds{Since: b.start}
sums[s] = h
}
h.Routed.Calls++
h.Routed.Tokens += int64(r.Input + r.Output)
h.Routed.CacheRead += int64(r.CacheRead)
h.Routed.CacheWrite += int64(r.CacheWrite)
if pr := priceOf(r); pr != nil {
h.Routed.Cost += r.CostAt(*pr)
} else {
unpriced[s] = true
}
}
})
if len(sums) == 0 {
return qs
}
out := make([]provider.SubscriptionQuota, len(qs))
copy(out, qs)
cloned := map[int]bool{}
for s, h := range sums {
if h.Routed.Tokens <= 0 || slices.ContainsFunc(inRun[s], func(k runKey) bool { return paidOtherwise[k] }) {
continue
}
q := &out[s.q]
if !cloned[s.q] { // the caller's windows are left as they are
q.Windows, cloned[s.q] = append([]provider.QuotaWindow(nil), q.Windows...), true
}
w := &q.Windows[s.w]
h.Used = w.Used
scale := 100 / w.Used
h.Tokens = int64(math.Round(float64(h.Routed.Tokens) * scale))
if !unpriced[s] && h.Routed.Cost > 0 {
h.Priced = true
h.Cost = h.Routed.Cost * scale
}
w.Holds = h
}
return out
}
// apiPricer is each call's model at its API list price: its maker's, else
// the provider's own list, never a price the user set for the
// subscription (which may well be nothing) nor a rate it bills at. A price
// of nothing at all is no API price.
func apiPricer() func(Record) *catalog.Price {
prices := map[[2]string]*catalog.Price{}
return func(r Record) *catalog.Price {
k := [2]string{r.Provider, r.Model}
if pr, ok := prices[k]; ok {
return pr
}
var pr *catalog.Price
v, ok := provider.MakerPrice(r.Model)
if !ok || v.Cost(1e6, 1e6, 0, 0) == 0 {
ok = false
if p, err := provider.Find(r.Provider); err == nil {
v, ok = p.ListPrice(r.Model)
}
}
if ok && v.Cost(1e6, 1e6, 0, 0) > 0 {
pr = &v
}
prices[k] = pr
return pr
}
}