Files
magpie/internal/usage/log_hash_cost_test.go
T
yetone f6a96b2f0b usage: a change time with a fraction settles in 100ms, so a read after an append hashes no log (#3394)
readLogSnapshot checks its snapshot against a SHA-256 of the log's whole
prefix whenever the log's change time is under a second old. Under steady
traffic every read came within a second of the gateway's last append, so
each one hashed the whole usage.jsonl again: 1.8 times the log for each
append and read. A stamp with a nonzero fraction of a second comes from a
clock that ticks in milliseconds (APFS in ns, Linux's coarse clock 1-10 ms,
NTFS ~15.6 ms), so it settles in logFineSettle = 100ms. A stamp in whole
seconds (HFS+, FAT, a share) keeps the one-second settle.

Run:
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/budget/: ok.
- TestUsageReadAfterAppendHashesNothingOnAFineClock (20000-row log, 5
  appends, each followed by two reads): fine stamp 0 bytes hashed;
  whole-second stamp 50.7 MB. Broken by hand (logFineSettle = time.Second):
  54 MB hashed, red.
- Real account, sandbox HOME, a deepseek-only providers.json and a 98 MB
  usage.jsonl (the owner's own log, repeated 50 times). magpie serve took
  30 real /v1/responses calls with a Codex user agent to
  deepseek/deepseek-flash, all answered, while /v1/magpie/usage?period=today
  (the Usage page's read) was polled every second. Process CPU time, two
  runs each: before 3.11 s and 3.05 s, after 1.95 s and 2.25 s. The same
  calls with /v1/magpie/quotas polled cost 0.2 s on both binaries, since
  that path never reads the log.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/ clean.

Not tried: an HFS+ or FAT volume (the test skips when the file system
gives whole-second stamps, and covers that case by truncating the stamp);
the full suite at this head runs after the push.
2026-10-24 21:00:05 +08:00

160 lines
5.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package usage
import (
"encoding/json"
"fmt"
"os"
"testing"
"time"
)
// While the gateway writes, the log's change time is nearly always under a
// second old, so each read verifies the snapshot by a fingerprint (#1357).
// The parse itself produces that fingerprint: a rebuild re-reads the file only
// to verify the prefix it continues and to check nothing was rewritten during
// the read, not a third time before the read. Hashing doesn't allocate, so
// the allocation tests don't see this; this counts the bytes re-read.
func TestUsageAppendReadHashesNoPreReadScan(t *testing.T) {
pageHome(t)
holdClock(t, time.Now())
historyLog(t, 20000)
now := logIndexNow
logIndexNow = func() time.Time { return time.Now().Add(2 * logStampSettle) }
Summarize(Today) // settled first, as a log the gateway hasn't touched for a while
logIndexNow = now
t.Cleanup(func() { logIndexNow = now })
hash := logRecordHash
var hashed int64
logRecordHash = func(path string, n int64) string {
hashed += n
return hash(path, n)
}
t.Cleanup(func() { logRecordHash = hash })
const cycles = 5
start := time.Now()
for range cycles {
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 1, Status: 200})
Summarize(Today)
}
took := time.Since(start)
info, err := os.Stat(Path())
if err != nil {
t.Fatal(err)
}
perCycle := hashed / cycles
t.Logf("log %d bytes: %d bytes hashed per append + read (%.2f× the log), %v per cycle", info.Size(), perCycle, float64(perCycle)/float64(info.Size()), took/cycles)
if s := Summarize(Today); s.Calls != 1+cycles {
t.Fatalf("calls today: %d", s.Calls)
}
// An unsettled append verifies its prefix and re-hashes after the read:
// two passes. A third, before the read, is the scan the parse replaces.
if perCycle > 2*info.Size()+info.Size()/10 {
t.Fatalf("an append + read hashed %d bytes over a %d-byte log, more than the prefix check and the after-read check", perCycle, info.Size())
}
}
// Another writer can be mid-line when a read stats the log. The fingerprint
// covers only the complete lines parsed, so the line's completion continues
// the snapshot rather than counting the half line as read.
func TestUsagePartialLineThenCompletion(t *testing.T) {
for _, settle := range []bool{false, true} {
t.Run(fmt.Sprint("settled=", settle), func(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Now())
if settle {
settleLogClock(t)
}
historyLog(t, logBlockRows+3)
line, err := json.Marshal(Record{Time: now, Agent: "codex", Provider: "relay", Model: "m", Session: "late", Input: 41, Status: 200})
if err != nil {
t.Fatal(err)
}
line = append(line, '\n')
half := len(line) / 2
write := func(b []byte) {
t.Helper()
f, err := os.OpenFile(Path(), os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(b); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
}
write(line[:half])
before := Summarize(All)
if s := readLogSnapshot(); s.hash != "" && s.hash != recordHash(Path(), s.off) {
t.Fatal("fingerprint does not cover the parsed bytes")
}
write(line[half:])
got, want := Summarize(All), summarize(All, now, Load(time.Time{}))
if got.Totals != want.Totals || got.Calls != before.Calls+1 {
t.Fatalf("completed line: got %+v (%d calls, %d before) want %+v", got.Totals, got.Calls, before.Calls, want.Totals)
}
equalPage(t, QueryPage(All, Filter{}, 0, 100), pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{})))
})
}
}
// Under steady traffic the gateway appends a call less than a second before
// most reads. A change time with a fraction of a second settles in
// logFineSettle, so a read that long after an append continues the
// snapshot from the appends it noted, hashing nothing again; one in whole
// seconds still waits out logStampSettle (#3394).
func TestUsageReadAfterAppendHashesNothingOnAFineClock(t *testing.T) {
for _, tc := range []struct {
name string
fine bool
hashes bool
}{{"fine stamp", true, false}, {"whole-second stamp", false, true}} {
t.Run(tc.name, func(t *testing.T) {
pageHome(t)
holdClock(t, time.Now())
historyLog(t, 20000)
changeTime, now := logChangeTime, logIndexNow
t.Cleanup(func() { logChangeTime, logIndexNow = changeTime, now })
if !tc.fine {
logChangeTime = func(info os.FileInfo) time.Time { return changeTime(info).Truncate(time.Second) }
}
// each read comes 150 ms after the append before it
logIndexNow = func() time.Time { return time.Now().Add(150 * time.Millisecond) }
Summarize(Today)
hash := logRecordHash
var hashed int64
logRecordHash = func(path string, n int64) string {
hashed += n
return hash(path, n)
}
t.Cleanup(func() { logRecordHash = hash })
const cycles = 5
for range cycles {
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 1, Status: 200})
if c := logChangeTime(mustStat(t)); tc.fine && c.Nanosecond() == 0 {
t.Skip("this file system keeps change times in whole seconds")
}
Summarize(Today)
Summarize(Today)
}
if s := Summarize(Today); s.Calls != 1+cycles {
t.Fatalf("calls today: %d", s.Calls)
}
t.Logf("%d bytes hashed over %d appends", hashed, cycles)
if tc.hashes != (hashed > 0) {
t.Fatalf("hashed %d bytes over %d appends and reads 150 ms after each", hashed, cycles)
}
})
}
}
func mustStat(t *testing.T) os.FileInfo {
t.Helper()
info, err := statLogFile(Path())
if err != nil {
t.Fatal(err)
}
return info
}