quota history: written without a value made for each point

Each new reading of any account wrote quota-history.json again, and
json.Marshal made each point's three times anew and the whole file
each time. On a live magpie (v0.1.2906, a 747 KB history, a dozen
accounts) that was 35.6 MB and ~306k allocations in two idle minutes,
a quarter of every allocation the process made then.

appendQuotaHist writes the same bytes into a buffer kept for the next
write, under quotaHistMu as every write is. What json.Marshal refuses
or writes its own way (a NaN, a year past 9999, an offset with
seconds) is still left to it.

Run on mote (macOS), at this tree:
- go vet ./internal/provider/, GOOS=windows go vet: clean; gofmt clean
- go test -count=1 ./internal/provider/: ok (133s)
- TestQuotaHistWrittenAsJSONMarshal: byte-equal to json.Marshal over
  random histories (zones, fractions, odd floats, nil maps and lines,
  HTML and U+2028 in names) and the refused cases.
- TestQuotaHistWriteAllocations: 6000 points, 68 allocations a write.
  Broken by hand (json.Marshal back): 18174, red.
- The real quota-history.json (a copy, deleted after): 746994 bytes,
  equal byte for byte; 141 allocations a write, json.Marshal 21319.

Not tried: a live magpie running this build; the numbers above are
the live profile's and the copy's.
This commit is contained in:
yetone
2026-11-06 12:05:01 +08:00
parent f86dd7910a
commit b4799a6bb7
3 changed files with 272 additions and 1 deletions
+1 -1
View File
@@ -109,7 +109,7 @@ var readQuotaHist = func() quotaHist {
}
func writeQuotaHist(h quotaHist) {
b, err := json.Marshal(h)
b, err := marshalQuotaHist(h)
if err != nil {
return
}
+151
View File
@@ -0,0 +1,151 @@
package provider
import (
"encoding/json"
"maps"
"math"
"slices"
"strconv"
"time"
)
// quotaHistBuf is what the history was last written from, under
// quotaHistMu, kept for the next write: the file is written again on
// each new reading of any account (a few times a minute with a dozen
// accounts), and json.Marshal made the whole of it anew each time, with
// three times for each point (~750 KB, ~300k allocations a minute on a
// live magpie, a quarter of all it allocated idle).
var quotaHistBuf []byte
// appendQuotaHist is json.Marshal(h) appended to b, byte for byte, made
// without a value of its own for each point; ok is false for what
// json.Marshal would refuse (a NaN, a year past 9999), which the caller
// leaves to it.
func appendQuotaHist(b []byte, h quotaHist) ([]byte, bool) {
if h == nil {
return append(b, "null"...), true
}
b = append(b, '{')
for i, key := range slices.Sorted(maps.Keys(h)) {
if i > 0 {
b = append(b, ',')
}
b = appendJSONString(b, key)
b = append(b, ':')
ws := h[key]
if ws == nil {
b = append(b, "null"...)
continue
}
b = append(b, '{')
for j, name := range slices.Sorted(maps.Keys(ws)) {
if j > 0 {
b = append(b, ',')
}
b = appendJSONString(b, name)
b = append(b, ':')
pts := ws[name]
if pts == nil {
b = append(b, "null"...)
continue
}
b = append(b, '[')
for k, p := range pts {
if k > 0 {
b = append(b, ',')
}
var ok bool
if b, ok = appendQuotaPoint(b, p); !ok {
return b, false
}
}
b = append(b, ']')
}
b = append(b, '}')
}
return append(b, '}'), true
}
func appendQuotaPoint(b []byte, p QuotaPoint) ([]byte, bool) {
var ok bool
b = append(b, `{"at":`...)
if b, ok = appendJSONTime(b, p.At); !ok {
return b, false
}
b = append(b, `,"left":`...)
if b, ok = appendJSONFloat(b, p.Left); !ok {
return b, false
}
if p.Start != nil {
b = append(b, `,"start":`...)
if b, ok = appendJSONTime(b, *p.Start); !ok {
return b, false
}
}
if p.ResetsAt != nil {
b = append(b, `,"resetsAt":`...)
if b, ok = appendJSONTime(b, *p.ResetsAt); !ok {
return b, false
}
}
return append(b, '}'), true
}
// appendJSONTime is time.Time's MarshalJSON appended to b: RFC 3339 with
// its fraction, for a year json.Marshal takes.
func appendJSONTime(b []byte, t time.Time) ([]byte, bool) {
if y := t.Year(); y < 0 || y > 9999 {
return b, false
}
if _, off := t.Zone(); off%60 != 0 {
return b, false // MarshalJSON refuses an offset with seconds in it
}
b = append(b, '"')
b = t.AppendFormat(b, time.RFC3339Nano)
return append(b, '"'), true
}
// appendJSONFloat is a float64 as encoding/json writes one.
func appendJSONFloat(b []byte, f float64) ([]byte, bool) {
if math.IsNaN(f) || math.IsInf(f, 0) {
return b, false
}
format := byte('f')
if a := math.Abs(f); a != 0 && (a < 1e-6 || a >= 1e21) {
format = 'e'
}
b = strconv.AppendFloat(b, f, format, -1, 64)
if format == 'e' {
// e-09 to e-9, as encoding/json does
if n := len(b); n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' {
b[n-2] = b[n-1]
b = b[:n-1]
}
}
return b, true
}
// appendJSONString is a string as json.Marshal writes it: as it is when
// nothing in it is escaped there.
func appendJSONString(b []byte, s string) []byte {
for i := 0; i < len(s); i++ {
if c := s[i]; c < 0x20 || c > 0x7e || c == '"' || c == '\\' || c == '<' || c == '>' || c == '&' {
q, _ := json.Marshal(s) // escaped as json.Marshal does
return append(b, q...)
}
}
b = append(b, '"')
b = append(b, s...)
return append(b, '"')
}
// marshalQuotaHist is h as the file holds it, in quotaHistBuf; under
// quotaHistMu. What it gives is overwritten by the next call.
func marshalQuotaHist(h quotaHist) ([]byte, error) {
b, ok := appendQuotaHist(quotaHistBuf[:0], h)
if !ok {
return json.Marshal(h)
}
quotaHistBuf = b
return b, nil
}
@@ -0,0 +1,120 @@
package provider
import (
"bytes"
"encoding/json"
"fmt"
"math"
"math/rand"
"testing"
"time"
)
// TestQuotaHistWrittenAsJSONMarshal holds the history's own writer to
// what json.Marshal wrote, byte for byte, for every shape the file can
// hold: another computer's points merged in keep their zone and their
// figures as sent.
func TestQuotaHistWrittenAsJSONMarshal(t *testing.T) {
r := rand.New(rand.NewSource(1))
east := time.FixedZone("x", 8*3600+30*60)
lefts := []float64{0, 100, 37.25, 0.01, 1e-7, -3, 1e21, 123456789.5, 5e-324, math.MaxFloat64, -0.0000012}
at := func() time.Time {
t := time.Date(2026, 1+time.Month(r.Intn(12)), 1+r.Intn(28), r.Intn(24), r.Intn(60), r.Intn(60), 0, time.UTC)
switch r.Intn(4) {
case 0:
return t.In(east)
case 1:
return t.Add(time.Duration(r.Intn(1e9)))
}
return t
}
h := quotaHist{
"codex|a@b.c": {"5 hours": nil, "Weekly": {}},
"claude|<x>&\"y\"": nil,
}
for i := range 30 {
ws := map[string][]QuotaPoint{}
for j := range 1 + r.Intn(4) {
var pts []QuotaPoint
for range r.Intn(40) {
p := QuotaPoint{At: at(), Left: lefts[r.Intn(len(lefts))]}
if r.Intn(2) == 0 {
p.Left = math.Round(r.Float64()*10000) / 100
}
if r.Intn(3) > 0 {
s := at()
p.ResetsAt = &s
}
if r.Intn(2) == 0 {
s := at()
p.Start = &s
}
pts = append(pts, p)
}
ws[fmt.Sprintf("window \u2028%d<%d>", j, i)] = pts
}
h[fmt.Sprintf("p%d|user%d@x.y", i, i)] = ws
}
want, err := json.Marshal(h)
if err != nil {
t.Fatal(err)
}
got, err := marshalQuotaHist(h)
if err != nil || !bytes.Equal(got, want) {
i := 0
for i < min(len(got), len(want)) && got[i] == want[i] {
i++
}
t.Fatalf("err %v; differs at %d:\n got %.120s\nwant %.120s", err, i, got[i:], want[i:])
}
for _, n := range []quotaHist{nil, {}} {
want, _ := json.Marshal(n)
if got, _ := marshalQuotaHist(n); !bytes.Equal(got, want) {
t.Fatalf("%v: got %s, want %s", n, got, want)
}
}
// what json.Marshal refuses or writes its own way it is left to: the
// same bytes, or the same refusal
far := time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)
odd := time.Date(2026, 1, 1, 0, 0, 0, 0, time.FixedZone("s", 30))
for _, bad := range []QuotaPoint{{At: far}, {At: odd}, {At: time.Now(), Left: math.NaN()}, {At: time.Now(), ResetsAt: &far}} {
b := quotaHist{"a|b": {"w": {bad}}}
want, werr := json.Marshal(b)
got, err := marshalQuotaHist(b)
if (werr == nil) != (err == nil) || !bytes.Equal(got, want) {
t.Fatalf("%v: json.Marshal %s %v, own %s %v", bad, want, werr, got, err)
}
}
}
// TestQuotaHistWriteAllocations: writing a full history again makes no
// value for each of its points; json.Marshal made three times' text and
// the whole file each write.
func TestQuotaHistWriteAllocations(t *testing.T) {
h := quotaHist{}
base := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
for a := range 12 {
ws := map[string][]QuotaPoint{}
for _, name := range []string{"5 hours", "Weekly"} {
var pts []QuotaPoint
for i := range 250 {
p := QuotaPoint{At: base.Add(time.Duration(i) * 5 * time.Minute), Left: float64(i%100) + 0.25}
r := p.At.Add(5 * time.Hour)
s := p.At
p.ResetsAt, p.Start = &r, &s
pts = append(pts, p)
}
ws[name] = pts
}
h[fmt.Sprintf("codex|user%d@example.com", a)] = ws
}
if _, err := marshalQuotaHist(h); err != nil {
t.Fatal(err)
}
// 6000 points: a dozen accounts' and windows' names and their sorting
// are what is left
n := testing.AllocsPerRun(5, func() { marshalQuotaHist(h) })
if n > 100 {
t.Fatalf("a write of 6000 points made %v allocations, want at most 100", n)
}
}