From 99fcddeeba2a28f8144b06400414ec9eefdd90cd Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 10 Oct 2026 23:41:53 +0800 Subject: [PATCH] usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean) Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in usage.jsonl. On Usage > Requests every filter, model pick and refresh spun forever and the page never updated. Reproduced in a sandbox HOME with 750k generated records in the real format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process. The cause: the #563 budget dropped the index's blocks once they passed 24 MB (60 MB here), so every read, of any period, parsed the whole file again (6 s CPU) and priced every call again; All took 12 s of CPU, the heatmap 13 s, and the page read both at once. What changed: - log_index: the gateway's blocks are always kept (about 80 bytes a call, S2-compressed instead of flate); the file is parsed once, then only what was appended. - block_price: the gateway's blocks are priced per query, once per set of provider/model/served/effort names rather than per call, into pooled buffers; range loops go by pointer (a packed row is 264 bytes). - request_page: pages are always cached (16 at most), session-file chunks stay in the budget, and a page asked again while it is worked out (the refresh button, the timer) waits for that one instead of starting a second scan. - Siblings that read the same history: - The heatmap names each day once. - A day filter no longer allocates per call. - The ledger behind the TUI, magpie usage, the CSV export and sync (LedgerOf, OwnDays) reads the gateway's calls from the index instead of Load parsing the whole file. - Direct/Summaries matches the session files' calls against the index's blocks without pricing all 750k gateway calls. - A summary of more than 1024 sessions is now cached with its top 1024 (it was not cached at all). The Usage page's /api/usage gets the top 100 (it was sent all 84k, 19 MB, which it never draws) plus a new sessionCount. /v1/magpie/usage still lists every session, and magpie usage says "top 10 of ". Timings, CPU (the box was at load 130-190 on 14 cores, so wall is inflated; min of repeated runs), before -> after: Requests today 6.0 s -> 20 ms Requests 7d 5.8 s -> 93 ms Requests 30d ~6 s -> 362 ms Requests all 12.4 s -> 2.4 s first, ~8 ms again all, model filter 12.3 s -> 1.5 s all, agent filter 11.3 s -> 1.8 s 30d, search "opus" 6.7 s -> 353 ms day filter 6.0 s -> ~0.1 s heatmap 13.7 s -> ~2.3 s first summary today / all 6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again /api/usage?period=all 1.6 s + 19 MB JSON each time -> <1 ms, 53 KB TUI Summaries(all) ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again TUI Summaries(today) ~6 s -> 29 ms Visit 7d (budget, codex) 5.9 s -> 10 ms The first read of the file after start costs ~5 s of CPU, once. Tests (each seen red with its guarantee broken by hand): - TestUsageOverBudgetHistoryIsReadOnce - TestUsageSessionChunksStayInBudget - TestUsageOverBudgetPageIsCached - TestUsagePageAskedTwiceIsWorkedOutOnce - TestUsageLedgerReadsTheIndexNotTheFile - TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached) - TestDirectCountsOnlySessionFileCalls, now with a request-id match, checks that Direct/Summaries equal the ledger's. Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and GOOS=windows go vet on the touched packages. --- docs/reference.md | 3 +- internal/gui/usage.go | 2 +- internal/usage/block_price.go | 146 +++++++++++++++++ internal/usage/cache_bounds_test.go | 229 ++++++++++++++++++++------- internal/usage/direct.go | 50 +++++- internal/usage/direct_test.go | 13 +- internal/usage/gateway_sessions.go | 5 +- internal/usage/heatmap.go | 11 +- internal/usage/ledger.go | 27 +++- internal/usage/log_index.go | 31 ++-- internal/usage/priced_blocks_test.go | 12 -- internal/usage/request_page.go | 208 ++++++++++++------------ internal/usage/request_snapshot.go | 68 +++++--- internal/usage/shared.go | 2 +- internal/usage/summary_cache.go | 66 +++++--- internal/usage/usage.go | 13 +- internal/usage/vias_cache.go | 5 +- internal/usageapi/usageapi.go | 15 +- usage_cli.go | 4 +- 19 files changed, 643 insertions(+), 267 deletions(-) create mode 100644 internal/usage/block_price.go diff --git a/docs/reference.md b/docs/reference.md index 432793eaa..559919823 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1427,7 +1427,8 @@ in `served.json` beside `providers.json`, so a restart keeps it. An app of your own can read the Usage page's numbers too. `GET /v1/magpie/usage?period=` is the page's summary, the same JSON as the window's `/api/usage` (`path` is left out for another -machine). `GET /v1/magpie/usage/requests` is its requests a page at a time +machine), with every session in `sessions` where the window's lists the +top 100 by tokens; `sessionCount` is how many there are. `GET /v1/magpie/usage/requests` is its requests a page at a time (`offset`, `limit` up to 500), with the same filters as the Requests log: `period`, `day`, `agent`, `provider`, `model`, `account`, `callerKey`, `purpose`, `failed`, `q`, `via`, `computer`. What was said in a call is not diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 88877bd93..6846667f4 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -31,7 +31,7 @@ type ( ) var ( - usageState = usageapi.State + usageState = usageapi.Page ledgerPage = usageapi.LedgerPage periodOf = usageapi.PeriodOf ledgerFilter = usageapi.FilterOf diff --git a/internal/usage/block_price.go b/internal/usage/block_price.go new file mode 100644 index 000000000..f1c7f1209 --- /dev/null +++ b/internal/usage/block_price.go @@ -0,0 +1,146 @@ +package usage + +import ( + "slices" + "sync" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// swapKnown marks a row whose Swapped flag was settled when it was priced, +// so reading it back needs no second look at the two names. +const swapKnown = 64 + +// pricedAs is what a gateway call is priced as, the same for every call of +// one provider, model, served model and effort. +type pricedAs struct { + provider string + flags uint8 + price *catalog.Price +} + +// blockPricer prices the gateway's raw blocks as a query reads them. What a +// row's price, provider id, swap and routing are depends on a few of its +// names only, so they are worked out once for each set of names, not once +// per call: 750k calls name a few hundred. +type blockPricer struct { + aliases map[string]string + wires map[string]string + price func(Record) *catalog.Price + by map[[4]string]pricedAs + agents map[string]string + pooled []*[]packedRow +} + +// pricedRows are the rows of the blocks a query priced, handed back when +// it is done with them: a query over the whole history decodes every block, +// and allocating and clearing their rows again each time was a third of it. +var pricedRows = sync.Pool{New: func() any { s := make([]packedRow, 0, logBlockRows); return &s }} + +// release hands the rows of the blocks it priced back, once the query no +// longer reads them (a page's rows are copies). +func (b *blockPricer) release() { + for _, rows := range b.pooled { + pricedRows.Put(rows) + } + b.pooled = nil +} + +func newBlockPricer(aliases, wires map[string]string, price func(Record) *catalog.Price) *blockPricer { + return &blockPricer{aliases: aliases, wires: wires, price: price, by: map[[4]string]pricedAs{}, agents: map[string]string{}} +} + +// as is priceRow's answer for a gateway call of these names. +func (b *blockPricer) as(prov, model, served, effort string) pricedAs { + k := [4]string{prov, model, served, effort} + if a, ok := b.by[k]; ok { + return a + } + if id, ok := b.aliases[prov]; ok { + prov = id + } + a := pricedAs{provider: prov, flags: swapKnown} + sent := provider.SentNameIn(b.wires, prov, model, effort) + if served != "" && Swapped(sent, served) && !(SameSpelled(model, served) || ServingName(model, served) || RelayRenamed(model, served)) { + a.flags |= 2 + } + if GroupRouted(sent, served) { + a.flags |= 32 + } + a.price = b.price(Record{Provider: prov, Model: model, Served: served, Effort: effort}) + b.by[k] = a + return a +} + +func (b *blockPricer) agent(ua string) string { + a, ok := b.agents[ua] + if !ok { + a = AgentOf(ua) + b.agents[ua] = a + } + return a +} + +// block is the priced copy of a raw block, made for one query and not kept. +func (b *blockPricer) block(packed *rowChunk) *rowChunk { + buf := pricedRows.Get().(*[]packedRow) + raw := packed.unpackInto(*buf) + // unpackInto decodes into the buffer whenever it is large enough + if raw != nil && raw != packed && cap(*buf) >= len(raw.Rows) { + b.pooled = append(b.pooled, buf) + } else { + pricedRows.Put(buf) + } + if raw == nil { + return nil + } + c := *raw + if raw == packed { + c.Rows = slices.Clone(raw.Rows) // a block too small to compress is shared + } + c.Strings = slices.Clip(c.Strings) + added := map[string]uint32{} + intern := func(s string, was uint32) uint32 { + if c.Strings[was] == s { + return was + } + if id, ok := added[s]; ok { + return id + } + id := uint32(len(c.Strings)) + c.Strings = append(c.Strings, s) + added[s] = id + return id + } + type ids struct { + provider uint32 + flags uint8 + price *catalog.Price + } + names := map[[4]uint32]ids{} + agents := map[uint32]uint32{} + for i := range c.Rows { + p := &c.Rows[i] + k := [4]uint32{p.Text[1], p.Text[5], p.Text[7], p.Text[8]} + got, ok := names[k] + if !ok { + a := b.as(c.Strings[k[0]], c.Strings[k[1]], c.Strings[k[2]], c.Strings[k[3]]) + got = ids{intern(a.provider, k[0]), a.flags, a.price} + names[k] = got + } + agent, ok := agents[p.Text[0]] + if !ok { + agent = intern(b.agent(c.Strings[p.Text[0]]), p.Text[0]) + agents[p.Text[0]] = agent + } + p.Text[0], p.Text[1] = agent, got.provider + p.Flags = p.Flags&^(1|2|32) | got.flags + p.Cost = 0 + if got.price != nil && p.Tokens[0]+p.Tokens[1] > 0 { + p.Flags |= 1 + p.Cost = got.price.CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5])) + } + } + return &c +} diff --git a/internal/usage/cache_bounds_test.go b/internal/usage/cache_bounds_test.go index 167a49928..0918c5874 100644 --- a/internal/usage/cache_bounds_test.go +++ b/internal/usage/cache_bounds_test.go @@ -2,8 +2,10 @@ package usage import ( "bytes" + "encoding/json" "fmt" "os" + "sync" "testing" "time" ) @@ -61,8 +63,8 @@ func TestUsageSameTickRewriteIsNotCached(t *testing.T) { historyLog(t, 1) Summarize(All) QueryPage(All, Filter{}, 0, 100) - warm := logSnapshotFor(true) - if warm.settled || logSnapshotFor(true) != warm { + warm := readLogSnapshot() + if warm.settled || readLogSnapshot() != warm { t.Fatal("unchanged same-tick metadata must reuse its fingerprint without becoming settled") } before, err := statLogFile(Path()) @@ -99,10 +101,10 @@ func TestUsageSameTickRewriteIsNotCached(t *testing.T) { } equalPage(t, QueryPage(All, Filter{}, 0, 100), pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{}))) logIndexNow = func() time.Time { return tick.Add(time.Hour) } - logSnapshotFor(true) // An oversized read publishes a metadata-only copy. - stable := logSnapshotFor(true) + readLogSnapshot() // An oversized read publishes a metadata-only copy. + stable := readLogSnapshot() for range 3 { - if logSnapshotFor(true) != stable { + if readLogSnapshot() != stable { t.Fatal("settled unchanged metadata was not cached") } } @@ -197,108 +199,217 @@ func cacheBudget(t *testing.T, n int64) { t.Cleanup(func() { requestCacheBytes = old }) } -func TestUsageRawCacheBudget(t *testing.T) { +// A history whose index is larger than the cache budget is still read from +// the file once: every later summary, page, filter, heatmap, Visit and Vias +// reads the kept blocks. Over the budget the blocks used to be dropped and +// each of them parsed the whole file again, 6 s of CPU at 750k calls, which +// left the Requests page spinning on every refresh and filter (Vantiboo1ean). +func TestUsageOverBudgetHistoryIsReadOnce(t *testing.T) { pageHome(t) now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) + settleLogClock(t) cacheBudget(t, 128) historyLog(t, 1034) - assertFresh := func() { + reads := func() int { + logIndex.Lock() + defer logIndex.Unlock() + return logIndex.reads + } + readAll := func() { t.Helper() cold := Load(time.Time{}) for _, p := range []Period{Today, Week, Month, All} { got, want := Summarize(p), summarize(p, now, cold) if got.Totals != want.Totals { - t.Fatalf("uncached %s summary stale: %+v / %+v", p, got.Totals, want.Totals) + t.Fatalf("%s summary: %+v / %+v", p, got.Totals, want.Totals) + } + for _, f := range []Filter{{}, {Model: "m"}, {Agent: "codex"}, {Query: "relay"}} { + equalPage(t, QueryPage(p, f, 0, 100), pageFromLedger(p, f, 0, 100, LedgerOf(p, f))) } - equalPage(t, QueryPage(p, Filter{}, 0, 100), pageFromLedger(p, Filter{}, 0, 100, LedgerOf(p, Filter{}))) - } - logIndex.Lock() - retained := len(logIndex.snapshot.blocks) - logIndex.Unlock() - if retained != 0 { - t.Fatalf("retained %d over-budget blocks", retained) - } - requestCache.Lock() - chunks, pages := len(requestCache.chunks)+len(requestCache.gateways), len(requestCache.pages) - requestCache.Unlock() - if chunks != 0 || pages != 0 { - t.Fatalf("uncached raw history retained chunks=%d pages=%d", chunks, pages) } + HeatmapOf(Filter{}) + Visit(now.AddDate(0, 0, -7), func(Record) {}) + Vias(now.AddDate(0, 0, -7)) + } + readAll() + before := reads() + readAll() + if n := reads() - before; n != 0 { + t.Fatalf("an unchanged over-budget history was parsed %d more times", n) } - assertFresh() Append(Record{Time: now, Agent: "codex", Provider: "relay", Model: "m", Input: 11}) - assertFresh() - historyLog(t, 20) // rewrite/truncate after the oversized metadata-only index - assertFresh() + before = reads() + readAll() + if n := reads() - before; n != 1 { + t.Fatalf("an append was read %d times, want once (from where the last read ended)", n) + } + historyLog(t, 20) // a rewrite is read again in full, once + before = reads() + readAll() + if n := reads() - before; n != 1 { + t.Fatalf("a rewrite was read %d times, want once", n) + } } -func TestUsageRawAndPricedChunksShareBudget(t *testing.T) { +// The session files' chunks stay within the budget; the gateway's index is +// kept whatever its size and is not counted against it. +func TestUsageSessionChunksStayInBudget(t *testing.T) { pageHome(t) holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) historyLog(t, 1034) - snapshot := readLogSnapshot() - cacheBudget(t, snapshot.bytes+1) + cacheBudget(t, 1) equalPage(t, QueryPage(All, Filter{}, 0, 100), pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{}))) requestCache.Lock() defer requestCache.Unlock() - retained := snapshot.bytes - for _, c := range requestCache.gateways { - retained += c.Bytes - } + var retained int64 for _, c := range requestCache.chunks { retained += c.Bytes } if retained > requestCacheBytes { - t.Fatalf("raw + priced bytes %d exceed %d", retained, requestCacheBytes) + t.Fatalf("session chunk bytes %d exceed %d", retained, requestCacheBytes) } } -func TestUsageLargeSummaryIsCompleteButNotCached(t *testing.T) { +func TestUsageLargeSummaryIsCompleteAndKeptTrimmed(t *testing.T) { pageHome(t) for i := 0; i < summaryCacheSessions+1; i++ { - Append(Record{Time: time.Now(), Agent: "codex", Provider: "relay", Model: "m", Session: fmt.Sprint(i), Input: 1}) + Append(Record{Time: time.Now(), Agent: "codex", Provider: "relay", Model: "m", Session: fmt.Sprint(i), Input: 1 + i}) + } + worked := func() int { + summaries.Lock() + defer summaries.Unlock() + return summaries.worked } got := Summarize(All) - if len(got.Sessions) != summaryCacheSessions+1 || got.Calls != summaryCacheSessions+1 { + if len(got.Sessions) != summaryCacheSessions+1 || got.Calls != summaryCacheSessions+1 || got.SessionCount != summaryCacheSessions+1 { t.Fatalf("large summary lost sessions: %d / %d", len(got.Sessions), got.Calls) } summaries.Lock() - _, kept := summaries.entries[All] + kept := summaries.entries[All] summaries.Unlock() - if kept { - t.Fatal("oversized Sessions retained in summary cache") + if len(kept.value.Sessions) != summaryCacheSessions || kept.value.SessionCount != summaryCacheSessions+1 { + t.Fatalf("the cache kept %d sessions of %d", len(kept.value.Sessions), kept.value.SessionCount) + } + // the Usage page and the TUI ask for the top few, and a long history's + // summary is not worked out again for them (Vantiboo1ean, ~750k + // requests in ~84k sessions); asked for all, it is + before := worked() + for _, n := range []int{0, 100, summaryCacheSessions} { + top := SummarizeTop(All, n) + if len(top.Sessions) != n || top.SessionCount != summaryCacheSessions+1 || top.Calls != got.Calls || n > 0 && top.Sessions[0] != got.Sessions[0] { + t.Fatalf("top %d: %d sessions of %d", n, len(top.Sessions), top.SessionCount) + } + } + if s, _ := Summaries(All); len(s.Sessions) != summaryCacheSessions || s.SessionCount != summaryCacheSessions+1 { + t.Fatalf("Summaries: %d sessions of %d", len(s.Sessions), s.SessionCount) + } + if n := worked() - before; n != 0 { + t.Fatalf("a summary of the top sessions was worked out %d more times", n) + } + if len(Summarize(All).Sessions) != summaryCacheSessions+1 || worked() != before+1 { + t.Fatal("asked for every session, the summary is not worked out afresh") + } + // what a caller is handed is its own + top := SummarizeTop(All, 10) + top.Sessions[0].Calls, top.Agents[0].Calls = -1, -1 + if again := SummarizeTop(All, 10); again.Sessions[0].Calls == -1 || again.Agents[0].Calls == -1 { + t.Fatal("a caller's change reached the cache") } } -// Rebuilding an uncached snapshot with a larger budget keeps its version and -// page key. The preceding query must leave an initialized page map to write. -func TestUsagePageCacheAfterUncachedQuery(t *testing.T) { +// A page of a history larger than the budget is kept, so asking it again +// (the Requests page's refresh with nothing new) costs nothing. +func TestUsageOverBudgetPageIsCached(t *testing.T) { pageHome(t) settleLogClock(t) holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) historyLog(t, 1034) - normalBudget := requestCacheBytes cacheBudget(t, 128) - QueryPage(All, Filter{}, 0, 100) - logIndex.Lock() - uncached := logIndex.snapshot.uncached - logIndex.Unlock() - if !uncached { - t.Fatal("fixture must exceed the tiny budget") - } - requestCache.Lock() - key := requestCache.key - requestCache.Unlock() - - requestCacheBytes = normalBudget got := QueryPage(All, Filter{}, 0, 100) equalPage(t, got, pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{}))) requestCache.Lock() defer requestCache.Unlock() - if requestCache.key != key { - t.Fatal("page key changed instead of exercising the same cache") - } if _, ok := requestCache.pages[pageKey{All, Filter{}, 0, 100}]; !ok { - t.Fatal("page not cached after rebuilding within budget") + t.Fatal("page of an over-budget history not cached") + } +} + +// A page asked for again while it is still being worked out waits for that +// one: the Requests page's refresh, pressed while a long history's All was +// read (Vantiboo1ean, ~750k calls), read the whole history once more beside +// it, and each press added another. +func TestUsagePageAskedTwiceIsWorkedOutOnce(t *testing.T) { + pageHome(t) + settleLogClock(t) + holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) + historyLog(t, 1034) + var mu sync.Mutex + builds := 0 + building = func() { + mu.Lock() + builds++ + mu.Unlock() + time.Sleep(300 * time.Millisecond) // the others ask while this one works + } + t.Cleanup(func() { building = nil }) + start := make(chan struct{}) + var wg sync.WaitGroup + pages := make([]RequestPage, 4) + for i := range pages { + wg.Go(func() { + <-start + pages[i] = QueryPage(All, Filter{}, 0, 100) + }) + } + close(start) + wg.Wait() + if builds != 1 { + t.Fatalf("the same page was worked out %d times at once, want 1", builds) + } + want := pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{})) + for _, p := range pages { + equalPage(t, p, want) + } +} + +// The TUI, magpie usage, the CSV export and sync read a period's ledger +// from the gateway's index, not by parsing usage.jsonl again: over +// Vantiboo1ean's ~750k requests each parse took seconds. What they read is +// what Load reads, appends and an unfinished last line included. +func TestUsageLedgerReadsTheIndexNotTheFile(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) + settleLogClock(t) + historyLog(t, 1034) + Summaries(Today) // the index is read + Append(Record{Time: now.Add(-time.Hour), Agent: "claude-code", Provider: "anthropic", Model: "claude-x", Requested: "magpie/x", Served: "claude-x-1", Session: "s2", Subagent: "sub", Input: 5, Output: 7, CacheRead: 3, CacheWrite: 2, CacheWrite1h: 1, Reasoning: 4, Status: 500, Error: "boom", ErrType: "overloaded", ProviderAccount: "a@b", Effort: "high", TTFT: 30, Millis: 90, Archive: "2026-09-30/x", Via: "mini", CallerKeyID: "k1", Rejected: true}) + f, err := os.OpenFile(Path(), os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteString(`{"t":"2026-09-30T11:59:00Z","agent":"codex"`); err != nil { + t.Fatal(err) + } + f.Close() + for _, since := range []time.Time{{}, now.AddDate(0, 0, -7), now.Add(-2 * time.Hour), now.Add(time.Hour)} { + got, want := gatewayRecords(since), Load(since) + g, _ := json.Marshal(got) + w, _ := json.Marshal(want) + if len(got) != len(want) || string(g) != string(w) { + t.Fatalf("since %v: the index read %d records, the file %d", since, len(got), len(want)) + } + } + mu.Lock() + before := loads + mu.Unlock() + Summaries(All) + Direct(Week) + LedgerOf(Month, Filter{}) + Ledger(Today, Filter{Model: "m"}) + OwnDays(now.AddDate(0, 0, -3)) + mu.Lock() + defer mu.Unlock() + if n := loads - before; n != 0 { + t.Fatalf("the ledger parsed the whole log %d times", n) } } diff --git a/internal/usage/direct.go b/internal/usage/direct.go index 62d5fc7bf..c7741604e 100644 --- a/internal/usage/direct.go +++ b/internal/usage/direct.go @@ -3,6 +3,8 @@ package usage import ( "sort" "time" + + "github.com/yetone/magpie/internal/sessions" ) // Direct is a period's calls the agents made on their own, which the gateway @@ -14,16 +16,57 @@ import ( // window's Usage tab but not in magpie usage). func Direct(p Period) Summary { now := Clock() - return direct(p, now, LedgerOfAt(p, Filter{}, now).Rows) + return direct(p, now, directRows(p, now)) } // Summaries is Summarize(p) and Direct(p) asked at one moment, for a page // that shows the two together: asked one after the other, midnight could // fall between them and set one day's calls through magpie beside the next -// day's calls not through it. +// day's calls not through it. The gateway's sessions are its top +// summaryCacheSessions (SummarizeTop), of its SessionCount: a page lists a +// few, and the summary of a long history is then kept rather than worked +// out again. func Summaries(p Period) (Summary, Summary) { now := Clock() - return indexedSummary(p, now), direct(p, now, LedgerOfAt(p, Filter{}, now).Rows) + return topSummary(p, now, summaryCacheSessions), direct(p, now, directRows(p, now)) +} + +// directRows are the rows of LedgerOfAt(p, Filter{}, now) that Direct sums, +// the calls the agents' session files record that the gateway did not see, +// worked out without the rest: the gateway's own calls are only matched +// against them, from the blocks of the ledger's index as they are, not each +// made into a priced row. Over a long history (Vantiboo1ean, ~750k +// requests) those were most of the TUI's and magpie usage's wait. +func directRows(p Period, now time.Time) []Row { + since, until := p.Since(now), p.Until(now) + reader := LogCalls + if reader == nil { + reader = sessions.Calls + } + logs, others := reader(since), sharedRecords(since) + matched := map[int]bool{} + if len(logs) > 0 { + local := &rowChunk{} + for i, c := range logs { + r := logRecord(c) + r.Agent = c.Agent + local.add(Row{Record: r}, c.Msg, int64(i), c.Error != "") + } + var gateways []*rowChunk + for _, b := range readLogSnapshot().blocks { + if !since.IsZero() && b.Latest.Before(since.Add(-24*time.Hour)) { + continue + } + if c := b.unpack(); c != nil { + gateways = append(gateways, c) + } + } + for ref := range matchedBlocks(gateways, []*rowChunk{local}, nil, since, false) { + matched[ref.Index] = true + } + } + rows, _, _, _ := ledgerMatched(since, until, Filter{}, nil, logs, others, matched) + return rows } func direct(p Period, now time.Time, rows []Row) Summary { @@ -69,5 +112,6 @@ func direct(p Period, now time.Time, rows []Row) Summary { return gs } s.Agents, s.Models, s.Accounts, s.Sessions = list(agents), list(models), list(accounts), list(sessions) + s.SessionCount = len(s.Sessions) return s } diff --git a/internal/usage/direct_test.go b/internal/usage/direct_test.go index e99e74fe1..10e2b2f51 100644 --- a/internal/usage/direct_test.go +++ b/internal/usage/direct_test.go @@ -32,12 +32,15 @@ func TestDirectCountsOnlySessionFileCalls(t *testing.T) { // while its Codex session file names Codex: the same call, not one of // the agents' own Append(Record{Time: now.Add(-30 * time.Minute), Agent: "miyi-helper", Provider: "codex", Model: "gpt-6", Input: 700, Output: 70, CacheRead: 300, Millis: 9000, Status: 200, Session: "h1"}) + // a Claude Code call the gateway saw, told by the request id both name + Append(Record{Time: now.Add(-3 * time.Hour), Agent: "claude-cli/2", Provider: "relay", Model: "m", Input: 9, Output: 9, Status: 200, Session: "g2", RequestID: "req_1"}) old := LogCalls LogCalls = func(time.Time) []sessions.Call { return []sessions.Call{ {Time: now.Add(-time.Hour), Agent: "codex", Session: "c1", Model: "gpt-6", Tokens: sessions.Tokens{Input: 1000, Output: 100}}, {Time: now.Add(-2 * time.Hour), Agent: "codex", Session: "c1", Model: "gpt-6", Tokens: sessions.Tokens{Input: 3000, Output: 300}}, {Time: now.Add(-30*time.Minute + 9500*time.Millisecond), Agent: "codex", Session: "h1", Model: "gpt-6", Tokens: sessions.Tokens{Input: 700, Output: 70, CacheRead: 300}}, + {Time: now.Add(-3*time.Hour + time.Minute), Agent: "claude-code", Session: "c2", Model: "m", RequestID: "req_1", Tokens: sessions.Tokens{Input: 9, Output: 9}}, } } t.Cleanup(func() { LogCalls = old }) @@ -55,8 +58,16 @@ func TestDirectCountsOnlySessionFileCalls(t *testing.T) { if d.Cost == 0 || d.Unpriced != 0 { t.Fatalf("not priced: %+v", d.Totals) } + // Direct and Summaries work the same out from the ledger's index + // without pricing the gateway's calls (Vantiboo1ean, ~750k requests) + _, both := Summaries(Month) + for _, got := range []Summary{Direct(Month), both} { + if got.Totals != d.Totals || len(got.Agents) != 1 || len(got.Models) != 1 || len(got.Sessions) != 1 || got.Sessions[0] != d.Sessions[0] { + t.Fatalf("Direct %+v, from the ledger %+v", got, d) + } + } // the gateway's calls are Summarize's alone - if s := Summarize(Month); s.Calls != 2 || len(s.Agents) != 2 { + if s := Summarize(Month); s.Calls != 3 || len(s.Agents) != 3 { t.Fatalf("summary %+v", s.Totals) } // a period that starts after the calls has none of them diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index 547364ed7..bba445b7e 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -96,7 +96,7 @@ var gatewayCache struct { // Retain a few window projections, not one copy for every native exclusion set. // The log snapshot version also detects rewrites and changes of config directory. func gatewayProjection(since time.Time) gatewayProjectionEntry { - snapshot := logSnapshotFor(true) + snapshot := readLogSnapshot() meta := usagePriceCacheKey(time.Now()) gatewayCache.Lock() defer gatewayCache.Unlock() @@ -105,9 +105,6 @@ func gatewayProjection(since time.Time) gatewayProjectionEntry { return e } } - if snapshot.uncached && len(snapshot.blocks) == 0 { - snapshot = readLogSnapshot() - } ss, _ := buildGatewaySessions(snapshot, since, nil) e := gatewayProjectionEntry{version: snapshot.version, meta: meta, since: since, sessions: ss, byID: make(map[string]int, len(ss))} for i, s := range ss { diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go index 7dea421fe..132bee9b9 100644 --- a/internal/usage/heatmap.go +++ b/internal/usage/heatmap.go @@ -61,11 +61,20 @@ func HeatmapOf(f Filter) Heatmap { func heatmapOf(since, now time.Time, visit func(add func(Row))) *Heatmap { h := &Heatmap{From: since.Format(time.DateOnly), To: now.In(time.Local).Format(time.DateOnly), Days: []Day{}} at := map[string]*Day{} + // a day's name is made once for each day, not for each of its calls + type ymd struct{ y, yd int } + names := map[ymd]string{} visit(func(r Row) { if r.IsRejected() || r.Time.Before(since) { return } - d := r.Time.In(time.Local).Format(time.DateOnly) + t := r.Time.In(time.Local) + k := ymd{t.Year(), t.YearDay()} + d, ok := names[k] + if !ok { + d = t.Format(time.DateOnly) + names[k] = d + } if d > h.To { return } diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 6d9202cc3..a2ec853a7 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -119,8 +119,11 @@ func (f Filter) computer(r Record) bool { } func (f Filter) keeps(r Record) bool { - if f.Day != "" && r.Time.In(time.Local).Format(time.DateOnly) != f.Day { - return false + if f.Day != "" { + var day [len(time.DateOnly)]byte + if string(r.Time.In(time.Local).AppendFormat(day[:0], time.DateOnly)) != f.Day { + return false + } } if f.CallerKey != "" && r.CallerKeyID != f.CallerKey { return false @@ -215,10 +218,21 @@ func LedgerOfAt(p Period, f Filter, now time.Time) Ledgered { if reader == nil { reader = sessions.Calls } - rows, sum, agents, providers := ledgerWithShared(since, p.Until(now), f, Load(gatewaySince), reader(since), sharedRecords(since)) + rows, sum, agents, providers := ledgerWithShared(since, p.Until(now), f, gatewayRecords(gatewaySince), reader(since), sharedRecords(since)) return Ledgered{rows, sum, agents, providers} } +// gatewayRecords is the gateway's calls from since on, as the ledger's index +// holds them: what Load reads, without parsing usage.jsonl again. The TUI, +// magpie usage and the CSV export read a period's ledger this way, and over +// a long history (Vantiboo1ean, ~750k requests) parsing the whole file took +// seconds for each. +func gatewayRecords(since time.Time) []Record { + var out []Record + Visit(since, func(r Record) { out = append(out, r) }) + return out +} + // Filtered narrows one snapshot without reloading either log or repricing rows. func (l Ledgered) Filtered(f Filter) Ledgered { if f == (Filter{}) { @@ -332,6 +346,12 @@ func ledgerWith(since time.Time, f Filter, recs []Record, logs []sessions.Call) // priced and judged here as this computer's are, and none from until on (a // picked range's end, #1492; zero for none). func ledgerWithShared(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall) (rows []Row, sum Totals, agents, providers []string) { + return ledgerMatched(since, until, f, recs, logs, others, gatewayMatches(recs, logs)) +} + +// ledgerMatched is ledgerWithShared with the session files' calls the +// gateway saw already told (matched, by their index in logs). +func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall, matched map[int]bool) (rows []Row, sum Totals, agents, providers []string) { renamed := provider.Renamed() // the upstream names in force now, read once for the lot: a row is // judged by the names standing today, which is what Ledger says, and @@ -340,7 +360,6 @@ func ledgerWithShared(since, until time.Time, f Filter, recs []Record, logs []se priceOf := pricer() rows = make([]Row, 0, len(recs)+len(logs)) agents, providers = []string{}, []string{} - matched := gatewayMatches(recs, logs) identities := newSessionResolver(logs) add := func(r Record, pr *catalog.Price, source string) { if a := AgentOf(r.Agent); !slices.Contains(agents, a) { diff --git a/internal/usage/log_index.go b/internal/usage/log_index.go index 9e0518146..7f25509af 100644 --- a/internal/usage/log_index.go +++ b/internal/usage/log_index.go @@ -23,12 +23,13 @@ const ( logStampSettle = time.Second ) -// Raw and priced chunks share the request cache budget. Oversized histories -// remain queryable but their raw blocks are rebuilt instead of retained. +// The blocks are always kept, however long the history: they are the index +// every reader shares, about 80 bytes a call compressed. Dropping them over a +// size budget (#563) made each read parse the whole file again, 6 s of CPU +// for 750k calls, on every refresh and filter of the Requests page. type logSnapshot struct { bytes int64 - uncached bool settled bool path string info os.FileInfo @@ -45,6 +46,7 @@ var logIndex struct { sync.Mutex snapshot *logSnapshot version uint64 + reads int // how many times the file was opened to be parsed, for the tests } var logIndexNow = time.Now @@ -57,11 +59,7 @@ var logAppends struct { base, last os.FileInfo } -func readLogSnapshot() *logSnapshot { return logSnapshotFor(false) } - -// Metadata-only callers can use cached results without rebuilding a history -// whose blocks do not fit the cache budget. -func logSnapshotFor(metadataOnly bool) *logSnapshot { +func readLogSnapshot() *logSnapshot { logIndex.Lock() defer logIndex.Unlock() path := Path() @@ -83,7 +81,7 @@ func logSnapshotFor(metadataOnly bool) *logSnapshot { unchanged = old.settled && settled } } - if unchanged && (!old.uncached || metadataOnly) { + if unchanged { return old } if !unchanged { @@ -103,11 +101,12 @@ func logSnapshotFor(metadataOnly bool) *logSnapshot { // The parse is the fingerprint: it hashes the lines it reads, continuing // the old snapshot's hash when it continues its blocks. sum := sha256.New() - if continued && !old.uncached && resumeLogHash(sum, old.digest) { + if continued && resumeLogHash(sum, old.digest) { next.off, next.first = old.off, old.first next.blocks = slices.Clone(old.blocks) next.keyProviders = maps.Clone(old.keyProviders) } + logIndex.reads++ f, err := os.Open(path) if err != nil { return next @@ -168,14 +167,7 @@ func logSnapshotFor(metadataOnly bool) *logSnapshot { for _, c := range next.blocks { next.bytes += c.Bytes } - if next.bytes > requestCacheBytes { - next.uncached = true - kept := *next - kept.blocks = nil - logIndex.snapshot = &kept - } else { - logIndex.snapshot = next - } + logIndex.snapshot = next return next } @@ -188,7 +180,8 @@ func (s *logSnapshot) visit(since time.Time, fn func(Record)) { if c == nil { continue } - for i, p := range c.Rows { + for i := range c.Rows { + p := &c.Rows[i] if !p.Time.Before(since) { fn(c.row(i).Record) } diff --git a/internal/usage/priced_blocks_test.go b/internal/usage/priced_blocks_test.go index d06d5fbbc..ba7ecb425 100644 --- a/internal/usage/priced_blocks_test.go +++ b/internal/usage/priced_blocks_test.go @@ -36,18 +36,6 @@ func TestRequestPageAppendDoesNotRepriceHistory(t *testing.T) { if grown := allocations - small; grown > 2000 { t.Fatalf("append re-read unchanged history: %.0f allocations over 8000 records, %.0f over 10", allocations, small) } - raw := readLogSnapshot().blocks[0] - requestCache.Lock() - before := requestCache.gateways[raw].Archive - requestCache.Unlock() - Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 1, Status: 200}) - QueryPage(All, Filter{}, 0, 100) - requestCache.Lock() - after := requestCache.gateways[raw].Archive - requestCache.Unlock() - if len(before) == 0 || len(after) == 0 || &before[0] != &after[0] { - t.Fatal("sealed gateway block was re-priced after append") - } for _, period := range []Period{All, Today, Week} { got := QueryPage(period, Filter{}, 0, 100) want := pageFromLedger(period, Filter{}, 0, 100, LedgerOf(period, Filter{})) diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index f3a2367c3..3af7c8eff 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -140,7 +140,7 @@ func (c *rowChunk) row(i int) Row { for i, s := range rowText(&r) { *s = c.Strings[p.Text[i]] } - if r.Swapped && (SameSpelled(r.Model, r.Served) || ServingName(r.Model, r.Served) || RelayRenamed(r.Model, r.Served)) { + if r.Swapped && p.Flags&swapKnown == 0 && (SameSpelled(r.Model, r.Served) || ServingName(r.Model, r.Served) || RelayRenamed(r.Model, r.Served)) { r.Swapped = false // kept before a name spelled otherwise, a vendor's serving name or a relay's rename was the same } r.Computer = c.Computer @@ -184,9 +184,24 @@ type requestIndex struct { sync.Mutex root, meta, key string chunks map[string]*rowChunk - gateways map[*rowChunk]*rowChunk // immutable raw block -> priced block pages map[pageKey]RequestPage tick uint64 + // flights are the pages being worked out: a second ask for one waits + // for it rather than reading the whole history beside it (a refresh + // pressed while a 750k-call All was still being read, Vantiboo1ean) + flights map[flightKey]*pageFlight +} + +// building, in tests, is told each time a page is worked out. +var building func() + +type flightKey struct { + key string + q pageKey +} +type pageFlight struct { + done chan struct{} + page RequestPage } var requestCache requestIndex @@ -216,7 +231,7 @@ func recordHash(path string, n int64) string { func QueryPage(p Period, f Filter, offset, limit int) RequestPage { return queryPage(p, f, offset, limit, sessions.ReadCallSource) } -func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.CallSource) []sessions.Call) RequestPage { +func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.CallSource) []sessions.Call) (page RequestPage) { if limit <= 0 { limit = 100 } @@ -257,7 +272,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C } meta += fmt.Sprintf("|%x|%s", h.Sum(nil), statKey(catalog.LivePath("antigravity"))) h.Reset() - snapshot := logSnapshotFor(true) + snapshot := readLogSnapshot() version := snapshot.version fmt.Fprint(h, meta, version, now.Format("2006-01-02 MST")) for _, s := range sources { @@ -275,7 +290,6 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C if idx.root != root || idx.meta != meta { idx.root, idx.meta = root, meta idx.chunks = map[string]*rowChunk{} - idx.gateways = map[*rowChunk]*rowChunk{} idx.pages = nil idx.key = "" } @@ -288,16 +302,33 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C idx.Unlock() return page } + fk := flightKey{key, q} + if fl := idx.flights[fk]; fl != nil { + idx.Unlock() + <-fl.done + return fl.page + } + if idx.flights == nil { + idx.flights = map[flightKey]*pageFlight{} + } + fl := &pageFlight{done: make(chan struct{})} + idx.flights[fk] = fl + defer func() { + requestCache.Lock() + if requestCache.flights[fk] == fl { + delete(requestCache.flights, fk) + } + requestCache.Unlock() + fl.page = page + close(fl.done) + }() idx.tick++ // Copy only metadata while holding the lock. Published chunks are immutable; // reading, decoding, pricing and aggregation use a private snapshot. shared := idx idx = &requestIndex{root: idx.root, meta: idx.meta, key: idx.key, tick: idx.tick, - chunks: maps.Clone(idx.chunks), gateways: maps.Clone(idx.gateways)} + chunks: maps.Clone(idx.chunks)} shared.Unlock() - if snapshot.uncached && len(snapshot.blocks) == 0 { - snapshot = readLogSnapshot() - } price := pricer() priceRow := func(r Record, source string) Row { sent := r.Model @@ -317,41 +348,18 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C if !since.IsZero() { gatewaySince = since.Add(-24 * time.Hour) } + // The gateway's blocks are priced as they are read, from a memo of each + // provider, model, served model and effort the block names: a priced + // copy of each block kept beside it doubled the index, and over the + // cache budget every query priced the whole history again. var gateways []*rowChunk - aliases := provider.Renamed() - live := make(map[*rowChunk]bool, len(snapshot.blocks)) + priced := newBlockPricer(provider.Renamed(), cfg.ModelWires, price) for _, packed := range snapshot.blocks { - live[packed] = true if !gatewaySince.IsZero() && packed.Latest.Before(gatewaySince) { continue } - cached := idx.gateways[packed] - c := cached.unpack() - if c == nil { - raw := packed.unpack() - if raw == nil { - continue - } - c = &rowChunk{} - // Cache the entire block: another period can reuse the same prices. - // Only the append tail changes; a tariff change clears all blocks. - for i, pr := range raw.Rows { - r := raw.row(i).Record - if id, ok := aliases[r.Provider]; ok { - r.Provider = id - } - c.add(priceRow(r, ""), "", pr.Order, false) - } - cached = c.freeze() - } - kept := *cached - kept.Used = idx.tick - idx.gateways[packed] = &kept - gateways = append(gateways, c) - } - for raw := range idx.gateways { - if !live[raw] { - delete(idx.gateways, raw) + if c := priced.block(packed); c != nil { + gateways = append(gateways, c) } } on := map[string]bool{} @@ -455,7 +463,11 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C if someShared { names = sharedNames() } - page := buildRequestBlocks(p, f, offset, limit, now, gateways, chunks, others, names) + if building != nil { + building() + } + page = buildRequestBlocks(p, f, offset, limit, now, gateways, chunks, others, names) + priced.release() shared.Lock() defer shared.Unlock() // A query for an older filesystem snapshot may finish after a newer one. @@ -472,33 +484,15 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C delete(shared.chunks, path) } } - for raw, c := range idx.gateways { - if prev := shared.gateways[raw]; prev == nil || prev.Used <= c.Used { - shared.gateways[raw] = c - } - } - for raw := range shared.gateways { - if !live[raw] { - delete(shared.gateways, raw) - } - } if len(shared.pages) >= 16 { shared.pages = map[pageKey]RequestPage{} } - if !snapshot.uncached { - shared.pages[q] = page - } - // Raw blocks are also retained by gateway-map keys: charge their bytes once. - bytes := snapshot.bytes - budget := int64(requestCacheBytes) - if snapshot.uncached { - budget = 0 - shared.pages = map[pageKey]RequestPage{} - } - + shared.pages[q] = page + // The session files' chunks are bounded; the gateway's index is not + // counted here, as it is kept whatever its size (log_index.go). + var bytes int64 type cachedChunk struct { path string - raw *rowChunk row *rowChunk } var kept []cachedChunk @@ -506,10 +500,6 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C bytes += c.Bytes kept = append(kept, cachedChunk{path: path, row: c}) } - for raw, c := range shared.gateways { - bytes += c.Bytes - kept = append(kept, cachedChunk{raw: raw, row: c}) - } slices.SortFunc(kept, func(a, b cachedChunk) int { if a.row.Used < b.row.Used { return -1 @@ -520,14 +510,10 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C return strings.Compare(a.path, b.path) }) for _, c := range kept { - if bytes <= budget { + if bytes <= requestCacheBytes { break } - if c.raw != nil { - delete(shared.gateways, c.raw) - } else { - delete(shared.chunks, c.path) - } + delete(shared.chunks, c.path) bytes -= c.row.Bytes } return page @@ -539,7 +525,8 @@ func visibleLocal(chunks []*rowChunk) map[rowRef]bool { duplicates := map[rowRef]bool{} seen := map[string]bool{} for _, c := range chunks { - for i, p := range c.Rows { + for i := range c.Rows { + p := &c.Rows[i] msg := c.Strings[p.Text[rowMsg]] if msg == "" { continue @@ -594,7 +581,8 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } byID := map[string][]rowRef{} for _, gateway := range gateways { - for i, p := range gateway.Rows { + for i := range gateway.Rows { + p := &gateway.Rows[i] if (p.Flags&4 != 0 || p.Text[1] == 0 && p.Status >= 400) || p.Time.Before(gatewaySince) { continue } @@ -605,7 +593,8 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } byRequest := map[string][]rowRef{} for _, c := range chunks { - for i, p := range c.Rows { + for i := range c.Rows { + p := &c.Rows[i] ref := rowRef{c, i} if skip[ref] || p.Time.Before(since) { continue @@ -637,7 +626,8 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } groups := map[matchKey]*matchGroup{} for _, gateway := range gateways { - for i, p := range gateway.Rows { + for i := range gateway.Rows { + p := &gateway.Rows[i] if used[rowRef{gateway, i}] || (p.Flags&4 != 0 || p.Text[1] == 0 && p.Status >= 400) || p.Time.Before(gatewaySince) { continue } @@ -663,7 +653,8 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo } candidates := map[rowRef]rowRef{} for _, c := range chunks { - for j, p := range c.Rows { + for j := range c.Rows { + p := &c.Rows[j] ref := rowRef{c, j} if skip[ref] || matched[ref] || p.Time.Before(since) { continue @@ -748,9 +739,10 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga all := append(append(slices.Clone(gateways), chunks...), others...) visit := func(fn func(rowRef, Row)) { for _, c := range all { - for i, pr := range c.Rows { + for i := range c.Rows { + pr := &c.Rows[i] // not a copy: a row is 264 bytes ref := rowRef{c, i} - if pr.Time.Before(since) || after(until, pr.Time) || skip[ref] || matched[ref] { + if pr.Time.Before(since) || after(until, pr.Time) || len(skip) > 0 && skip[ref] || len(matched) > 0 && matched[ref] { continue } fn(ref, c.row(i)) @@ -759,9 +751,9 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga } out := RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}} agents, providers := map[string]bool{}, map[string]bool{} - purposes := map[string]bool{} + kinds := map[string]bool{} callers := map[string]*Group{} - accounts := map[string]*Group{} + accounts := map[[2]string]*Group{} computers := map[string]*Share{} groups := map[string]map[string]*Share{} chartGroups := map[string]map[string]*Share{} @@ -789,10 +781,19 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga viaFilter := f viaFilter.Through = "" var first time.Time + // the rows the chart and the heatmap count, kept as the first pass + // finds them so that theirs needn't read every row of the period again + var charted []rowRef visit(func(ref rowRef, r Row) { - agents[r.Agent] = true - purposes[PurposeOf(r.Kind)] = true - if r.Provider != "" { + // looked up before they are set: most rows name what an earlier + // one did, and a map's lookup is cheaper than its write + if !agents[r.Agent] { + agents[r.Agent] = true + } + if !kinds[r.Kind] { + kinds[r.Kind] = true + } + if r.Provider != "" && !providers[r.Provider] { providers[r.Provider] = true } addCallerRow(callers, r) @@ -826,6 +827,7 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga return } if keep || f.Day != "" && chartFilter.keepsRow(r) { + charted = append(charted, ref) for _, d := range Dimensions { k := keys.key(r, d) s := seriesGroups[d][k] @@ -907,6 +909,10 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga out.Providers = append(out.Providers, a) } slices.Sort(out.Providers) + purposes := map[string]bool{} + for kind := range kinds { + purposes[PurposeOf(kind)] = true + } for purpose := range purposes { out.Purposes = append(out.Purposes, purpose) } @@ -933,17 +939,15 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga out.Series[i].By[d] = map[string]Part{} } } - visit(func(_ rowRef, r Row) { - if !chartFilter.keepsRow(r) || r.IsRejected() { - return - } + for _, ref := range charted { + r := ref.row() t := r.Time.In(time.Local) if t.Before(chartSince) { - return + continue } i := bucketIndex(out.Bucket, chartSince, t) if i < 0 || i >= len(out.Series) { - return + continue } pt := &out.Series[i] pt.addRow(r) @@ -953,14 +957,12 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga part.add(r) pt.By[d][k] = part } - }) + } if p == heatmapPeriod { out.Heat = heatmapOf(since, now, func(add func(Row)) { - visit(func(_ rowRef, r Row) { - if chartFilter.keepsRow(r) { - add(r) - } - }) + for _, ref := range charted { + add(ref.row()) + } }) } // Match LedgerSeries's top-24 selection on the filtered data, not facets. @@ -1007,7 +1009,7 @@ func pageFromLedgerAt(p Period, f Filter, offset, limit int, all Ledgered, now t out.Through.addRow(r) } } - callers, accounts := map[string]*Group{}, map[string]*Group{} + callers, accounts := map[string]*Group{}, map[[2]string]*Group{} purposes := map[string]bool{} for i := len(all.Rows) - 1; i >= 0; i-- { purposes[PurposeOf(all.Rows[i].Kind)] = true @@ -1100,21 +1102,21 @@ func addCallerRow(groups map[string]*Group, r Row) { // Account choices cover the period too: each account that answered a call, // by provider, for the Account filter, whatever else is picked. -func addAccountRow(groups map[string]*Group, r Row) { +func addAccountRow(groups map[[2]string]*Group, r Row) { who := r.Account() if who == "" || r.IsRejected() { return } - id := r.Provider + "@" + who - g := groups[id] + k := [2]string{r.Provider, who} + g := groups[k] if g == nil { - g = &Group{ID: id, Provider: r.Provider, Account: who} - groups[id] = g + g = &Group{ID: r.Provider + "@" + who, Provider: r.Provider, Account: who} + groups[k] = g } g.addRow(r) } -func callerGroups(groups map[string]*Group) []Group { +func callerGroups[K comparable](groups map[K]*Group) []Group { out := make([]Group, 0, len(groups)) for _, g := range groups { out = append(out, *g) diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index 72ca1df9d..b59db851e 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -3,21 +3,25 @@ package usage // Cache snapshots encode the fixed request fields without reflection. The // encoding is private to this process: no on-disk format or migration. Time // locations are retained separately so a round trip preserves displayed times. +// +// The blocks are compressed with S2, not flate: a query over the whole +// history decodes every block, and flate's decoder was most of the 3 s a +// filter over 750k calls took; S2 decodes at memory speed for a block a +// little larger. import ( - "bytes" - "compress/flate" "encoding/binary" - "io" "math" + "slices" "sync" "time" "unsafe" + + "github.com/klauspost/compress/s2" ) -var rowCompressors = sync.Pool{New: func() any { - w, _ := flate.NewWriter(io.Discard, flate.BestSpeed) - return w -}} +// rowDecodes are the buffers blocks are decoded into before their rows are +// read out of them; nothing keeps a reference to one after unpack. +var rowDecodes = sync.Pool{New: func() any { return new([]byte) }} func (c *rowChunk) pack() *rowChunk { if c == nil || len(c.Rows) < 64 || len(c.Archive) != 0 { @@ -33,7 +37,8 @@ func (c *rowChunk) pack() *rowChunk { } var locations []*time.Location locs := map[*time.Location]uint64{} - for _, p := range c.Rows { + for k := range c.Rows { + p := &c.Rows[k] loc := p.Time.Location() id, ok := locs[loc] if !ok { @@ -57,33 +62,32 @@ func (c *rowChunk) pack() *rowChunk { put(uint64(p.Status)) put(uint64(p.Flags)) } - var b bytes.Buffer - w := rowCompressors.Get().(*flate.Writer) - w.Reset(&b) - _, err := w.Write(data) - closeErr := w.Close() - w.Reset(io.Discard) - rowCompressors.Put(w) - if err != nil || closeErr != nil || int64(b.Len()) >= c.Bytes { + archive := s2.Encode(nil, data) + if int64(len(archive)) >= c.Bytes { return c } next := *c next.Rows, next.Strings, next.dict = nil, nil, nil - next.Archive, next.Locations = b.Bytes(), locations + next.Archive, next.Locations = slices.Clip(archive), locations next.Bytes = int64(len(next.Archive) + len(locations)*8) return &next } -func (c *rowChunk) unpack() *rowChunk { +func (c *rowChunk) unpack() *rowChunk { return c.unpackInto(nil) } + +// unpackInto is unpack decoding the rows into rows when it is large enough: +// every field of a row is written, so a reused slice needs no clearing. +func (c *rowChunk) unpackInto(into []packedRow) *rowChunk { if c == nil || len(c.Archive) == 0 { return c } - r := flate.NewReader(bytes.NewReader(c.Archive)) - data, err := io.ReadAll(r) - r.Close() + buf := rowDecodes.Get().(*[]byte) + defer rowDecodes.Put(buf) + data, err := s2.Decode((*buf)[:cap(*buf)], c.Archive) if err != nil { return nil } + *buf = data valid := true take := func() uint64 { n, k := binary.Uvarint(data) @@ -100,16 +104,32 @@ func (c *rowChunk) unpack() *rowChunk { } next := *c next.Archive, next.Locations = nil, nil - next.Rows = make([]packedRow, int(rows)) + if uint64(cap(into)) >= rows { + next.Rows = into[:rows] + } else { + next.Rows = make([]packedRow, int(rows)) + } next.Strings = make([]string, int(strs)) next.Bytes = int64(len(next.Rows)) * int64(unsafe.Sizeof(packedRow{})) - for i := range next.Strings { + // The strings are copied out in one piece: one allocation a block, not + // one a string. + at := make([]int, 0, 2*int(strs)) + section := data + for range next.Strings { n := take() if n > uint64(len(data)) { return nil } - next.Strings[i] = string(data[:n]) + at = append(at, len(section)-len(data), int(n)) data = data[n:] + } + if !valid { + return nil + } + text := string(section[:len(section)-len(data)]) + for i := range next.Strings { + from, n := at[2*i], at[2*i+1] + next.Strings[i] = text[from : from+n] next.Bytes += int64(n) + 16 } for i := range next.Rows { diff --git a/internal/usage/shared.go b/internal/usage/shared.go index 8b706049a..173537564 100644 --- a/internal/usage/shared.go +++ b/internal/usage/shared.go @@ -104,7 +104,7 @@ func OwnDays(since time.Time) map[string][]SharedCall { if reader == nil { reader = sessions.Calls } - rows, _, _, _ := ledgerWith(since, Filter{}, Load(since.Add(-24*time.Hour)), reader(since)) + rows, _, _, _ := ledgerWith(since, Filter{}, gatewayRecords(since.Add(-24*time.Hour)), reader(since)) out := map[string][]SharedCall{} for i := len(rows) - 1; i >= 0; i-- { // oldest first r := rows[i] diff --git a/internal/usage/summary_cache.go b/internal/usage/summary_cache.go index 0d57ffb49..138c06fd0 100644 --- a/internal/usage/summary_cache.go +++ b/internal/usage/summary_cache.go @@ -18,54 +18,72 @@ const summaryCacheSessions = 1024 type summaryEntry struct { version uint64 meta string - value Summary + // value keeps the top summaryCacheSessions sessions only, of its + // SessionCount + value Summary } var summaries struct { sync.Mutex entries map[Period]summaryEntry + worked int // how many summaries were worked out, for the tests } -func indexedSummary(p Period, now time.Time) Summary { +func indexedSummary(p Period, now time.Time) Summary { return topSummary(p, now, -1) } + +// SummarizeTop is Summarize with only the top n sessions by tokens (all of +// them for n < 0); SessionCount says how many the period has. It is what a page that +// shows a few of them or none asks for: a summary of more than +// summaryCacheSessions sessions is kept with those only, and Summarize, which +// gives every one, works it out again each time. Over a long history +// (Vantiboo1ean, ~750k requests in ~84k sessions) that was every refresh of +// the Usage page and the TUI, and the page was sent all 84k. +func SummarizeTop(p Period, n int) Summary { return topSummary(p, Clock(), n) } + +func topSummary(p Period, now time.Time, n int) Summary { p = p.shown() - snapshot := logSnapshotFor(true) + snapshot := readLogSnapshot() + work := func() Summary { + summaries.Lock() + summaries.worked++ + summaries.Unlock() + return summarizeFrom(p, now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) }) + } if p.IsRange() { // a picked range is read afresh each time, so ranges never pile up // in the cache (#1492) - if snapshot.uncached && len(snapshot.blocks) == 0 { - snapshot = readLogSnapshot() - } - return summarizeFrom(p, now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) }) + return topOf(work(), n) } meta := usagePriceCacheKey(now) summaries.Lock() old, ok := summaries.entries[p] summaries.Unlock() - if ok && old.version == snapshot.version && old.meta == meta { - return cloneSummary(old.value) - } - if snapshot.uncached && len(snapshot.blocks) == 0 { - snapshot = readLogSnapshot() - } - value := summarizeFrom(p, now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) }) - // Keep every session in the returned result; limit retained cache data only. - if len(value.Sessions) > summaryCacheSessions { - summaries.Lock() - if previous := summaries.entries[p]; previous.version <= snapshot.version { - delete(summaries.entries, p) - } - summaries.Unlock() - return value + if ok && old.version == snapshot.version && old.meta == meta && (n >= 0 && n <= len(old.value.Sessions) || old.value.SessionCount == len(old.value.Sessions)) { + return topOf(cloneSummary(old.value), n) } + value := work() + // the cache keeps a copy with the top sessions only; the answer has as + // many as asked + kept := value + kept.Sessions = kept.Sessions[:min(len(kept.Sessions), summaryCacheSessions)] + kept = cloneSummary(kept) summaries.Lock() if summaries.entries == nil { summaries.entries = map[Period]summaryEntry{} } if previous := summaries.entries[p]; previous.version <= snapshot.version { - summaries.entries[p] = summaryEntry{snapshot.version, meta, value} + summaries.entries[p] = summaryEntry{snapshot.version, meta, kept} } summaries.Unlock() - return cloneSummary(value) + return topOf(value, n) +} + +// topOf is s with its top n sessions (all for n < 0). +func topOf(s Summary, n int) Summary { + if n >= 0 && len(s.Sessions) > n { + s.Sessions = s.Sessions[:n:n] + } + return s } // The exported result remains owned by its caller. diff --git a/internal/usage/usage.go b/internal/usage/usage.go index d3c32a8ff..1169b1344 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -157,6 +157,10 @@ func Path() string { return filepath.Join(filepath.Dir(provider.Path()), "usage. var mu sync.Mutex +// loads counts Load's reads of the whole log, for the tests: the ledger +// reads the gateway's calls from its index instead. +var loads int + // Append writes one record. Errors are swallowed: accounting must never // break a call. func Append(r Record) { @@ -192,6 +196,7 @@ func (r Record) IsRejected() bool { return r.Rejected || r.Provider == "" && r.S // not retained by a global cache after the caller finishes with this snapshot. func Load(since time.Time) []Record { mu.Lock() + loads++ f, err := os.Open(Path()) mu.Unlock() if err != nil { @@ -554,8 +559,11 @@ type Summary struct { // account that answered (#557) Accounts []Group `json:"accounts"` CallerKeys []Group `json:"callerKeys"` - // Sessions are the calls that named their session, by session. - Sessions []Group `json:"sessions"` + // Sessions are the calls that named their session, by session, the + // most tokens first: all of them, or the top few of SessionCount where + // it was asked for that way (SummarizeTop). + Sessions []Group `json:"sessions"` + SessionCount int `json:"sessionCount"` } // Summarize caches the four periods over an indexed log snapshot. Callers @@ -752,6 +760,7 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[ s.Sessions = append(s.Sessions, *g) } byTokens(s.Sessions) + s.SessionCount = len(s.Sessions) return s } diff --git a/internal/usage/vias_cache.go b/internal/usage/vias_cache.go index 8cd33e84c..cc6c80d63 100644 --- a/internal/usage/vias_cache.go +++ b/internal/usage/vias_cache.go @@ -14,14 +14,11 @@ var viasCache struct { } func cachedVias(since time.Time) map[string][]Via { - snapshot := logSnapshotFor(true) + snapshot := readLogSnapshot() viasCache.Lock() defer viasCache.Unlock() value := viasCache.value if value == nil || viasCache.version != snapshot.version || !viasCache.since.Equal(since) { - if snapshot.uncached && len(snapshot.blocks) == 0 { - snapshot = readLogSnapshot() - } value = buildVias(snapshot, since) if snapshot.info != nil && snapshot.off == snapshot.info.Size() { viasCache.version, viasCache.since, viasCache.value = snapshot.version, since, value diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go index 247770d9a..68b9e0566 100644 --- a/internal/usageapi/usageapi.go +++ b/internal/usageapi/usageapi.go @@ -62,8 +62,19 @@ type Usage struct { // State is the Usage page's summary of a period: what /api/usage and the // gateway's GET /v1/magpie/usage answer. -func State(p usage.Period) Usage { - s := usage.Summarize(p) +func State(p usage.Period) Usage { return stateOf(usage.Summarize(p)) } + +// PageSessions is how many sessions Page lists: the Usage page draws none of +// them, and SessionCount says how many there are. +const PageSessions = 100 + +// Page is State with the top PageSessions sessions only, which is what the +// Usage page asks for: over a long history (Vantiboo1ean, ~750k requests) +// State sent the page every one of ~84k sessions (22 MB) and worked the +// summary out again for each refresh. +func Page(p usage.Period) Usage { return stateOf(usage.SummarizeTop(p, PageSessions)) } + +func stateOf(s usage.Summary) Usage { out := Usage{Summary: s, Agents: []Group{}, Models: []Group{}, Accounts: []Group{}, Path: Tilde(usage.Path())} agents := clients() for _, g := range s.Agents { diff --git a/usage_cli.go b/usage_cli.go index f6b9a0436..b0b736cf2 100644 --- a/usage_cli.go +++ b/usage_cli.go @@ -185,8 +185,8 @@ func printUsage(out io.Writer, s stats.Summary, title string, names map[string]s if len(s.Sessions) > 0 { top := s.Sessions[:min(len(s.Sessions), 10)] head := "sessions" - if len(s.Sessions) > len(top) { - head = fmt.Sprintf("sessions · top %d of %d", len(top), len(s.Sessions)) + if s.SessionCount > len(top) { + head = fmt.Sprintf("sessions · top %d of %d", len(top), s.SessionCount) } table(head, top, func(g stats.Group) string { n := names[g.Agent]