usage: a turned page reuses the last pairing while its chunks are the same
A Requests page paired every Codex session file's calls with the
gateway's again on each query: clone, fold forks, match response ids.
That unpacked every session chunk three times and was about half of a
warm page (#3493). pairRowsMemo names the chunks of a pairing by their
serials (the probe chunk, which has none, by its rows' log offsets and
times) and keeps what the pairing found: the rows left out (skip,
matched), the actors it changed and each chunk's compactions. The next
query over the same chunks and window applies that to fresh clones
instead of pairing again. A changed file gets a new serial, a new
window or period misses, and adopt drops the memos with the parts.
Run at a6399dd49 (= origin/main, fetched):
- TestRequestPairsReusedAcrossPages (new): a gateway call paired with
its rollout, a fork copying another file's call and a Claude call,
every page of All/Today/Week at limit 1 and the whole page against
pageFromLedger. Broken by hand three ways, each red on the memo hit:
apply without matched ("all page 1: 4 rows, 157 input"), without skip
("4 rows, 127 input"), without compactions (page differs).
- Real data, same process (scratch test, not committed), fresh pairRows
vs the memo applied over a second read: sandbox with the live
rollouts (symlinked, read only) and a copy of usage.jsonl: All 15607
chunks, 4801 skip, 1469 matched, 2 actor sets; Today 58 matched; 7d
1075 matched. Actors, compactions, skip, matched equal, and pages
equal for 3 filters per period. Without the gateway log: All 15600
chunks, 4801 skip, all periods equal.
- Timing on that sandbox (load 110-143), page turns after the first:
v0.1.1449 mean 407 / 460 ms, this change 154 / 145 ms.
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...
./internal/sessions/...: usageapi and sessions ok; usage red only on
TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp,
which is #3511 (taken by another session). At -count=20, load 154,
it fails 3/20 here and 2/20 at the base 1313b047f; it builds no page.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.
Not tried: the GUI against a live gateway; the page reads the same
QueryPage the tests and the real-data run used.
This commit is contained in:
@@ -101,6 +101,8 @@ type partKey struct {
|
||||
// the index keeps for the next.
|
||||
type partCache struct {
|
||||
old, next map[uint64]*chunkPart
|
||||
// pairs is the last pairing of the period, and pairsNext this page's
|
||||
pairs, pairsNext *pairMemo
|
||||
}
|
||||
|
||||
// partSets bounds the partKeys kept: a page is open on one period and
|
||||
|
||||
@@ -482,6 +482,9 @@ type requestIndex struct {
|
||||
// names a call changes (meta), and read without the lock, since a
|
||||
// part is never written once made
|
||||
parts map[partKey]map[uint64]*chunkPart
|
||||
// pairs are the last pairing of each of a few periods (pairMemo),
|
||||
// kept as parts are
|
||||
pairs map[Period]*pairMemo
|
||||
}
|
||||
|
||||
// heatPage is a heatmap's page, of the gateway log's snapshot version,
|
||||
@@ -669,7 +672,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
var cache *partCache
|
||||
pk := partKey{p: p, f: f, since: p.Since(now), until: p.Until(now), loc: now.Location()}
|
||||
if p.Last() == 0 && p != heatmapPeriod {
|
||||
cache = &partCache{old: idx.parts[pk], next: map[uint64]*chunkPart{}}
|
||||
cache = &partCache{old: idx.parts[pk], next: map[uint64]*chunkPart{}, pairs: idx.pairs[p]}
|
||||
}
|
||||
shared := idx
|
||||
idx = shared.private()
|
||||
@@ -695,6 +698,14 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
shared.parts = map[partKey]map[uint64]*chunkPart{}
|
||||
}
|
||||
shared.parts[pk] = cache.next
|
||||
if shared.pairs == nil || len(shared.pairs) >= partSets && shared.pairs[p] == nil {
|
||||
shared.pairs = map[Period]*pairMemo{}
|
||||
}
|
||||
if cache.pairsNext != nil {
|
||||
shared.pairs[p] = cache.pairsNext
|
||||
} else {
|
||||
delete(shared.pairs, p)
|
||||
}
|
||||
}
|
||||
if len(shared.pages) >= 16 {
|
||||
shared.pages = map[pageKey]RequestPage{}
|
||||
@@ -894,6 +905,7 @@ func (idx *requestIndex) adopt(st requestState) {
|
||||
idx.pages = nil
|
||||
idx.heats = nil
|
||||
idx.parts = nil
|
||||
idx.pairs = nil
|
||||
idx.key = ""
|
||||
}
|
||||
if idx.key != st.key {
|
||||
@@ -1361,7 +1373,12 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.Time,
|
||||
// cache's for the chunks it has them for (nil: every chunk's read).
|
||||
func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string, identities map[string]sessions.CodexIdentity, cache *partCache) RequestPage {
|
||||
since := p.Since(now)
|
||||
ps := pairRows(p, now, gateways, chunks, others, identities)
|
||||
var ps *pairedRows
|
||||
if cache != nil {
|
||||
ps, cache.pairsNext = pairRowsMemo(p, now, gateways, chunks, others, identities, cache.pairs)
|
||||
} else {
|
||||
ps = pairRows(p, now, gateways, chunks, others, identities)
|
||||
}
|
||||
out := RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}}
|
||||
chartFilter := f
|
||||
chartFilter.Day = ""
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// pairMemo is what pairRows found over one list of chunks, named by their
|
||||
// serials: which rows another one stands for, and the Codex actors and
|
||||
// compactions it gave each chunk. A page turned, or asked for again
|
||||
// before anything changed, unpacked every session file three times over to
|
||||
// pair the same rows again: about half of a warm page (#3493).
|
||||
type pairMemo struct {
|
||||
since, until time.Time
|
||||
// serials are the chunks' in pairRows' order, each set ended by a 0;
|
||||
// a chunk without a serial (the probes') is named by its rows instead
|
||||
serials []uint64
|
||||
skip, matched []serialRef
|
||||
actors map[uint64][]string
|
||||
compactions map[uint64]map[int]*bool
|
||||
}
|
||||
|
||||
type serialRef struct {
|
||||
serial uint64
|
||||
index int
|
||||
}
|
||||
|
||||
// pairSerials names the chunks of a pairing, or is false when two have
|
||||
// no serial and so can't be told apart.
|
||||
func pairSerials(sets ...[]*rowChunk) ([]uint64, bool) {
|
||||
var out []uint64
|
||||
unnamed := false
|
||||
for _, set := range sets {
|
||||
for _, c := range set {
|
||||
s := c.serial
|
||||
if s == 0 {
|
||||
if unnamed || len(c.Archive) != 0 {
|
||||
return nil, false
|
||||
}
|
||||
unnamed = true
|
||||
s = unnamedSerial(c)
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
out = append(out, 0)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// unnamedSerial stands for a chunk made again for each query, the probes':
|
||||
// its rows are named by their place in the log and their time.
|
||||
func unnamedSerial(c *rowChunk) uint64 {
|
||||
h := mix(6, uint64(len(c.Rows)))
|
||||
for i := range c.Rows {
|
||||
h = mix(h, uint64(c.Rows[i].Order), uint64(c.Rows[i].Time.UnixNano()))
|
||||
}
|
||||
return h | 1
|
||||
}
|
||||
|
||||
// pairRowsMemo is pairRows, through old when it paired these chunks over
|
||||
// the same window. The memo it returns is for the next call (nil: none).
|
||||
func pairRowsMemo(p Period, now time.Time, gateways, chunks, others []*rowChunk, identities map[string]sessions.CodexIdentity, old *pairMemo) (*pairedRows, *pairMemo) {
|
||||
since, until := p.Since(now), p.Until(now)
|
||||
serials, ok := pairSerials(gateways, chunks, others)
|
||||
if !ok {
|
||||
return pairRows(p, now, gateways, chunks, others, identities), nil
|
||||
}
|
||||
if old != nil && old.since.Equal(since) && old.until.Equal(until) && slices.Equal(old.serials, serials) {
|
||||
return old.apply(serials, identities, gateways, chunks, others), old
|
||||
}
|
||||
ps := pairRows(p, now, gateways, chunks, others, identities)
|
||||
return ps, memoOf(ps, serials, append(append(slices.Clone(gateways), chunks...), others...))
|
||||
}
|
||||
|
||||
// memoOf is ps as a memo; originals are the chunks ps.all was cloned from.
|
||||
func memoOf(ps *pairedRows, serials []uint64, originals []*rowChunk) *pairMemo {
|
||||
m := &pairMemo{since: ps.since, until: ps.until, serials: serials}
|
||||
named := make(map[*rowChunk]uint64, len(ps.all))
|
||||
k := 0
|
||||
for i, c := range ps.all {
|
||||
for serials[k] == 0 {
|
||||
k++
|
||||
}
|
||||
named[c] = serials[k]
|
||||
k++
|
||||
if !slices.Equal(c.codexActors, originals[i].codexActors) {
|
||||
if m.actors == nil {
|
||||
m.actors = map[uint64][]string{}
|
||||
}
|
||||
m.actors[serials[k-1]] = c.codexActors
|
||||
}
|
||||
if c.codexCompactions != nil {
|
||||
if m.compactions == nil {
|
||||
m.compactions = map[uint64]map[int]*bool{}
|
||||
}
|
||||
m.compactions[serials[k-1]] = c.codexCompactions
|
||||
}
|
||||
}
|
||||
refs := func(set map[rowRef]bool) []serialRef {
|
||||
out := make([]serialRef, 0, len(set))
|
||||
for ref := range set {
|
||||
out = append(out, serialRef{named[ref.Chunk], ref.Index})
|
||||
}
|
||||
return out
|
||||
}
|
||||
m.skip, m.matched = refs(ps.skip), refs(ps.matched)
|
||||
return m
|
||||
}
|
||||
|
||||
// apply is the pairing m remembers, on clones of these chunks.
|
||||
func (m *pairMemo) apply(serials []uint64, identities map[string]sessions.CodexIdentity, sets ...[]*rowChunk) *pairedRows {
|
||||
var all []*rowChunk
|
||||
by := make(map[uint64]*rowChunk, len(serials))
|
||||
k := 0
|
||||
for _, set := range sets {
|
||||
for _, c := range cloneCodexChunks(set) {
|
||||
s := serials[k]
|
||||
k++
|
||||
if a, ok := m.actors[s]; ok {
|
||||
c.codexActors = a
|
||||
}
|
||||
c.codexCompactions = m.compactions[s]
|
||||
c.codexIdentities = identities
|
||||
by[s] = c
|
||||
all = append(all, c)
|
||||
}
|
||||
k++
|
||||
}
|
||||
refs := func(list []serialRef) map[rowRef]bool {
|
||||
out := make(map[rowRef]bool, len(list))
|
||||
for _, ref := range list {
|
||||
out[rowRef{by[ref.serial], ref.index}] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
return &pairedRows{all: all, skip: refs(m.skip), matched: refs(m.matched), since: m.since, until: m.until}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// A page turned over the same chunks reuses the last pairing. It must give
|
||||
// the page a fresh pairing gives: a gateway call its rollout stands for is
|
||||
// counted once, and so is a call a forked file copies, on every page
|
||||
// and in the sums.
|
||||
func TestRequestPairsReusedAcrossPages(t *testing.T) {
|
||||
pageHome(t)
|
||||
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
|
||||
dir := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30")
|
||||
writeCodexIdentity(t, "main-a", "native-main", "vscode")
|
||||
writeCodexCall(t, filepath.Join(dir, "rollout-2026-09-30T10-00-00-main-a.jsonl"), "main-a", "native-main", `"vscode"`, "resp-paired", "m", "low", now.Add(-time.Minute), 60, 6)
|
||||
writeCodexCall(t, filepath.Join(dir, "rollout-2026-09-30T10-00-01-solo-b.jsonl"), "solo-b", "native-solo", `"vscode"`, "resp-solo", "m", "low", now.Add(-2*time.Minute), 30, 3)
|
||||
// A fork copies solo-b's call; it is counted once.
|
||||
writeCodexCall(t, filepath.Join(dir, "rollout-2026-09-30T10-00-02-fork-c.jsonl"), "fork-c", "native-solo", `"vscode"`, "resp-solo", "m", "low", now.Add(-2*time.Minute), 30, 3)
|
||||
Append(Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 60, Output: 6, Status: 200, ResponseID: "resp-paired"})
|
||||
Append(Record{Time: now.Add(-3 * time.Hour), Agent: "claude", Provider: "openai", Model: "m", Input: 7, Output: 1, Status: 200})
|
||||
|
||||
for _, p := range []Period{All, Today, Week} {
|
||||
want := pageFromLedger(p, Filter{}, 0, 100, LedgerOf(p, Filter{}))
|
||||
if want.Total != 3 || want.Sum.Input != 97 {
|
||||
t.Fatalf("%v: fixture pairs to %d rows, %d input", p, want.Total, want.Sum.Input)
|
||||
}
|
||||
for offset := 0; offset < 3; offset++ {
|
||||
got := QueryPage(p, Filter{}, offset, 1)
|
||||
if got.Total != 3 || got.Sum.Input != 97 || len(got.Rows) != 1 {
|
||||
t.Fatalf("%v page %d: %d rows, %d input, %d shown", p, offset, got.Total, got.Sum.Input, len(got.Rows))
|
||||
}
|
||||
if got.Rows[0].ResponseID != want.Rows[offset].ResponseID || got.Rows[0].Input != want.Rows[offset].Input {
|
||||
t.Fatalf("%v page %d: %+v, want %+v", p, offset, got.Rows[0].Record, want.Rows[offset].Record)
|
||||
}
|
||||
}
|
||||
equalPage(t, QueryPage(p, Filter{}, 0, 100), want)
|
||||
equalPage(t, QueryPage(p, Filter{Query: "main-a"}, 0, 100), pageFromLedger(p, Filter{Query: "main-a"}, 0, 100, LedgerOf(p, Filter{Query: "main-a"})))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user