Files
magpie/internal/gui/trace_tallies_test.go
T
yetoneandggbdpq bdc1617bed routing: Accounts and keys count the whole day, not the last kept requests (#3351)
1234fsdc: the live Routing page's Accounts and keys said tried and
answered over the requests the page still keeps in memory, so on a busy
day the counts were a sliver of what Usage showed for the same accounts
and went down as old requests fell off. /api/trace/history (the read the
live page already makes every 15s) now carries `tallies`: per account or
key, today's tries, answers, fails by reason, models answered, the last
answer and the latest rest, read from routing/<today>.jsonl. The page
seeds the list with them and still takes the latest rest and readings
from the requests it keeps; a day looked at, or a purpose picked, counts
its own list as before. The note says "over today's requests" then.
Ported from ggbdpq's patch on the issue.

Changed from the patch:
- The patch parsed the whole day's file under history.mu on every look.
  A busy day's file is hundreds of MB (#3383) and saveRoute takes the
  same lock, so every 15s poll would stall the routes being written.
  DayTallies now folds in only the whole lines added since the last
  look (it keeps the offset, as History does); a line still being
  written waits for its end. It starts again when the day changes, the
  file shrank or was compressed, or the folder moved (another HOME).
- What it returns is a copy: the patch handed out the live tallies,
  and the JSON writer read a Fails map the next fold wrote.
- The latest name and rest go by the try's time, so no sort per look.
- docs/subsystems/gui-shell.md says how the counts are made and that a
  request done since the last look is counted at the next one.

Run on mote at this change on 394a92f0f. The pushed parent 5787d758a
adds usage, tray, redact and search changes and none of this change's
files:
- gofmt -l clean; go vet ./internal/gateway ./internal/gui for darwin,
  windows, and linux -tags nogui.
- go test ./internal/gateway -race -run 'History|DayTallies': ok.
- go test ./internal/gui -count=1 -timeout 45m: red in 11 tests, all
  red on main too. Ten are real-window AppKit tests killed at their
  deadline on mote (the same ten at 03f3e1528, #4125).
  TestSettingsSaveKeepsWhatItDoesNotSend is SearchAll on main (#4514).
  TestLiveHistoryTalliesTheWholeDay passes. At the pushed head, -run
  'Budget|Tallies': ok.
- GUI on WSL (wsl-run, Ubuntu 24.04, Playwright 1.62.0, Chromium and
  WebKit, every language each file runs):
  - The 229 test files that reach the Routing page, plus i18n-keys, at
    this change on 576b5dcbc (--test-concurrency=4): 3498 tests, 101 red
    in 31 files.
  - Those 31 files on main 03f3e1528: 94 red. With this change: 99 red.
    The same tests fail; which language or engine goes red changes from
    run to run (#4121, #4471).
  - Four of them run alone: 27 red on main, 21 with the change.
  - At 394a92f0f, routing-day-tallies, i18n-keys, account-weight,
    key-weight and routing-weight-chip passed. routing-columns' WebKit
    rows were red, as on main (#4520). Its fixture has no tallies.

Broken by hand:
- DayTallies re-reading the whole file each look (reset always true):
  TestDayTalliesFoldOnlyWhatWasAdded red, "a look after one route read
  101 lines, want 1".
- handing out the live tallies, no copy: red, "a tally handed out
  changed after: ... fails map[rate:3]".

Not tried: a real day's file of hundreds of MB. The first look after a
start still reads the whole day once under history.mu, as History's own
first read does. A real app beside a running gateway. Past days
are unchanged: still counted over their latest historyMax routes.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 11:29:38 +08:00

102 lines
3.8 KiB
Go

package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// The Routing page's accounts and keys counted each account's tried and
// answered over the last few requests the gateway keeps in memory, while
// the day tabs right above it counted the day's whole history — the two
// pages could disagree by orders of magnitude (#3351). The history read
// the live page already polls now carries the day's tallies, counted from
// the same files the Usage page reads, so its counts cover the day and
// not the last sixty requests.
func TestLiveHistoryTalliesTheWholeDay(t *testing.T) {
sandboxHome(t)
old := served.Swap(nil)
t.Cleanup(func() { served.Store(old) })
if err := os.MkdirAll(gateway.HistoryDir(), 0o700); err != nil {
t.Fatal(err)
}
write := func(rs []gateway.Route) {
t.Helper()
f, err := os.OpenFile(filepath.Join(gateway.HistoryDir(), time.Now().Local().Format("2006-01-02")+".jsonl"),
os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
enc := json.NewEncoder(f)
for _, r := range rs {
if enc.Encode(r) != nil {
t.Fatal("a route the gateway would have written")
}
}
f.Close()
}
// ninety requests weighed and tried on one account, then ten on
// another: the trace keeps the last sixty alone, so the live page's
// own counting could only ever name a fraction of the busy one's day
start := time.Now().Local().Add(-2 * time.Hour).Truncate(time.Second)
var rs []gateway.Route
for i := 0; i < 100; i++ {
w := gateway.Weighed{ID: "p/A", Provider: "p", Name: "P", Kind: "account", Who: "A", Model: "m"}
if i >= 90 {
w = gateway.Weighed{ID: "p/B", Provider: "p", Name: "P", Kind: "account", Who: "B", Model: "m"}
}
try := gateway.Try{ID: w.ID, Start: start.Add(time.Duration(i) * time.Minute), Done: true, Millis: 100, Status: 200}
if i == 0 || i == 45 { // two of the busy account's tries were turned away
try.Status, try.Fail = 429, "rate"
}
rs = append(rs, gateway.Route{ID: int64(i + 1), Time: try.Start, Done: true,
Model: "m", Provider: "p", Order: []gateway.Weighed{w}, Tries: []gateway.Try{try}})
}
write(rs)
ask := func() map[string]struct {
Tried int `json:"tried"`
OK int `json:"ok"`
Fails map[string]int `json:"fails"`
} {
mux := http.NewServeMux()
traceRoutes(mux)
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/gateway/history?day=", nil))
var out struct {
Tallies map[string]struct {
Tried int `json:"tried"`
OK int `json:"ok"`
Fails map[string]int `json:"fails"`
} `json:"tallies"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatalf("the history read: %v %s", err, w.Body)
}
return out.Tallies
}
// the page groups an account by its provider and its user, however it
// is weighed into a request; the tallies speak the same keying
got := ask()
busy, quiet := got[`["p","a"]`], got[`["p","b"]`]
if busy.Tried != 90 || busy.OK != 88 || busy.Fails["rate"] != 2 {
t.Errorf("the busy account's day: tried %d, answered %d, fails %v", busy.Tried, busy.OK, busy.Fails)
}
if quiet.Tried != 10 || quiet.OK != 10 {
t.Errorf("the quiet account's day: tried %d, answered %d", quiet.Tried, quiet.OK)
}
// a day that has grown since is counted again, not served stale
try := gateway.Try{ID: "p/B", Start: start.Add(3 * time.Hour), Done: true, Millis: 50, Status: 200}
write([]gateway.Route{{ID: 101, Time: try.Start, Done: true, Model: "m", Provider: "p",
Order: []gateway.Weighed{{ID: "p/B", Provider: "p", Name: "P", Kind: "account", Who: "B", Model: "m"}},
Tries: []gateway.Try{try}}})
if got = ask(); got[`["p","b"]`].Tried != 11 {
t.Errorf("the day grown, the quiet account's day: tried %d", got[`["p","b"]`].Tried)
}
}