diff --git a/internal/usage/request_disk.go b/internal/usage/request_disk.go new file mode 100644 index 000000000..04f896ec7 --- /dev/null +++ b/internal/usage/request_disk.go @@ -0,0 +1,307 @@ +package usage + +import ( + "bufio" + "encoding/binary" + "errors" + "hash/crc32" + "io" + "os" + "path/filepath" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// The session files' chunks are kept on disk between runs (requests-v1.bin). +// A started magpie opened every session file's call shard (~15.6k of them) +// and turned each call into a row again before its first Requests page +// could show, and so did a page asked for once two idle minutes had trimmed +// the chunks (#3493). An entry stands for its session file while the file's +// size and mtime are the same, as a call shard does, and the whole file +// while the binary that wrote it and what prices and names a call (the +// index's root and meta) are the same. +// +// The file is a header, then entries one after another, each its length, +// its CRC-32 and its bytes; a bad entry ends the read, and the entries +// before it stand. + +const requestDiskMagic = "magpie-requests-v1\n" + +func requestDiskPath() string { + return filepath.Join(filepath.Dir(sessions.CachePath()), "requests-v1.bin") +} + +// requestDiskBinary names the binary a file was written by: a new build may +// make a row of a call differently. +var requestDiskBinary = func() string { + exe, err := os.Executable() + if err != nil { + return "" + } + return statKey(exe) +} + +// requestDiskLeast is how many session files must want reading before the +// file is read for them: a page after a call reads one or two again. +var requestDiskLeast = 64 + +// diskHeader is the file's first entry. +func diskHeader(binary, root, meta string) []byte { + var b []byte + for _, s := range []string{requestDiskMagic, binary, root, meta} { + b = appendDiskString(b, s) + } + return b +} + +func appendDiskString(b []byte, s string) []byte { + b = binary.AppendUvarint(b, uint64(len(s))) + return append(b, s...) +} + +// diskEntry is c as an entry, or nil when it can't be kept: a chunk of +// another computer's day, or one whose times are in a zone that can't be +// named again. +func diskEntry(c *rowChunk) []byte { + if c.Computer != "" { + return nil + } + archive, locations := c.Archive, c.Locations + if len(archive) == 0 { + archive, locations = c.encode(func([]byte) bool { return true }) + } + var b []byte + put := func(v uint64) { b = binary.AppendUvarint(b, v) } + s := c.Source + for _, t := range []string{s.Path, s.Key, s.Agent} { + b = appendDiskString(b, t) + } + put(uint64(s.Size)) + put(uint64(s.Modified.UnixNano())) + put(uint64(c.Count)) + put(uint64(c.Latest.UnixNano())) + put(uint64(len(locations))) + for _, loc := range locations { + name, offset := time.Unix(0, 0).In(loc).Zone() + if loc == time.Local { + name = "Local" + } else if loc != time.UTC && loc.String() != name { + // a zone of the tz database, named by it + name = "@" + loc.String() + } + b = appendDiskString(b, name) + put(uint64(int64(offset))) + } + put(uint64(len(c.codexActors))) + for _, actor := range c.codexActors { + b = appendDiskString(b, actor) + } + put(uint64(len(archive))) + return append(b, archive...) +} + +var errDiskEntry = errors.New("bad requests entry") + +// readDiskEntry is the chunk an entry holds. +func readDiskEntry(b []byte) (*rowChunk, error) { + take := func() uint64 { + n, k := binary.Uvarint(b) + if k <= 0 { + b = nil + return 0 + } + b = b[k:] + return n + } + text := func() (string, bool) { + n := take() + if b == nil || n > uint64(len(b)) { + return "", false + } + s := string(b[:n]) + b = b[n:] + return s, true + } + c := &rowChunk{} + var ok [3]bool + c.Source.Path, ok[0] = text() + c.Source.Key, ok[1] = text() + c.Source.Agent, ok[2] = text() + if ok != [3]bool{true, true, true} { + return nil, errDiskEntry + } + c.Source.Size = int64(take()) + c.Source.Modified = time.Unix(0, int64(take())) + c.Count = int(take()) + c.Latest = time.Unix(0, int64(take())).In(time.Local) + n := take() + if b == nil || n > uint64(len(b)) { + return nil, errDiskEntry + } + for range n { + name, good := text() + offset := int(int64(take())) + if !good || b == nil { + return nil, errDiskEntry + } + var loc *time.Location + switch { + case name == "Local": + loc = time.Local + case name == "UTC": + loc = time.UTC + case len(name) > 0 && name[0] == '@': + l, err := time.LoadLocation(name[1:]) + if err != nil { + return nil, err + } + loc = l + default: + loc = time.FixedZone(name, offset) + } + c.Locations = append(c.Locations, loc) + } + n = take() + if b == nil || n > uint64(len(b)) { + return nil, errDiskEntry + } + for range n { + actor, good := text() + if !good { + return nil, errDiskEntry + } + c.codexActors = append(c.codexActors, actor) + } + n = take() + if b == nil || n != uint64(len(b)) || n == 0 { + return nil, errDiskEntry + } + c.Archive = b + c.Bytes = int64(len(b)+len(c.Locations)*8) + codexActorBytes(c.codexActors) + return c, nil +} + +// readDiskEntries hands each entry of the file at path to each in turn, +// while the file is of binary, root and meta. raw is the entry's bytes, +// whole, to be written on as they are. +func readDiskEntries(path, binary, root, meta string, each func(raw []byte) bool) { + in, err := os.Open(path) + if err != nil { + return + } + defer in.Close() + r := bufio.NewReaderSize(in, 1<<20) + header, ok := nextDiskEntry(r) + if !ok || string(header) != string(diskHeader(binary, root, meta)) { + return + } + for { + raw, ok := nextDiskEntry(r) + if !ok || !each(raw) { + return + } + } +} + +func nextDiskEntry(r *bufio.Reader) ([]byte, bool) { + n, err := binary.ReadUvarint(r) + if err != nil || n == 0 || n > 256<<20 { + return nil, false + } + var sum [4]byte + if _, err := io.ReadFull(r, sum[:]); err != nil { + return nil, false + } + b := make([]byte, n) + if _, err := io.ReadFull(r, b); err != nil || crc32.ChecksumIEEE(b) != binary.LittleEndian.Uint32(sum[:]) { + return nil, false + } + return b, true +} + +func writeDiskEntry(w *bufio.Writer, b []byte) error { + var head [binary.MaxVarintLen64 + 4]byte + n := binary.PutUvarint(head[:], uint64(len(b))) + binary.LittleEndian.PutUint32(head[n:], crc32.ChecksumIEEE(b)) + if _, err := w.Write(head[:n+4]); err != nil { + return err + } + _, err := w.Write(b) + return err +} + +// fromDisk puts in idx the chunks the file holds of the sources in want, +// each still the size and mtime it was. idx is a private copy (private). +func (idx *requestIndex) fromDisk(want map[string]sessions.CallSource) { + readDiskEntries(requestDiskPath(), requestDiskBinary(), idx.root, idx.meta, func(raw []byte) bool { + c, err := readDiskEntry(raw) + if err != nil { + return false + } + s, ok := want[c.Source.Path] + if !ok || s.Size != c.Source.Size || !s.Modified.Equal(c.Source.Modified) { + return true + } + c.Source = s + c.serial = nextChunkSerial() + c.Used = idx.tick + idx.chunks[s.Path] = c + return true + }) +} + +// toDisk writes chunks, and the entries of the file before it for the +// paths in on that chunks doesn't hold, as the file for root and meta. +func toDisk(root, meta string, chunks map[string]*rowChunk, on map[string]bool) error { + path, binary := requestDiskPath(), requestDiskBinary() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + out, err := os.CreateTemp(filepath.Dir(path), "requests-*.tmp") + if err != nil { + return err + } + defer os.Remove(out.Name()) + w := bufio.NewWriterSize(out, 1<<20) + err = writeDiskEntry(w, diskHeader(binary, root, meta)) + for _, c := range chunks { + if err != nil { + break + } + if b := diskEntry(c); b != nil { + err = writeDiskEntry(w, b) + } + } + if err == nil { + readDiskEntries(path, binary, root, meta, func(raw []byte) bool { + p, ok := diskEntryPath(raw) + if !ok { + return false + } + if on[p] && chunks[p] == nil { + err = writeDiskEntry(w, raw) + } + return err == nil + }) + } + if err == nil { + err = w.Flush() + } + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return os.Rename(out.Name(), path) +} + +// diskEntryPath is the path of the source an entry is of. +func diskEntryPath(b []byte) (string, bool) { + n, k := binary.Uvarint(b) + if k <= 0 || n > uint64(len(b)-k) { + return "", false + } + return string(b[k : k+int(n)]), true +} diff --git a/internal/usage/request_disk_test.go b/internal/usage/request_disk_test.go new file mode 100644 index 000000000..c11017729 --- /dev/null +++ b/internal/usage/request_disk_test.go @@ -0,0 +1,113 @@ +package usage + +import ( + "fmt" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/sessions" +) + +// A started magpie reads the session files' chunks from the file the last +// one wrote, and reads again only the session files that changed since; a +// file of other prices, or a bad one, is read past. Every page is the one +// the ledger gives. +func TestRequestChunksFromDisk(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local)) + least := requestDiskLeast + requestDiskLeast = 2 + t.Cleanup(func() { requestDiskLeast = least }) + dir := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30") + writeCodexIdentity(t, "main-a", "native-main", "vscode") + rollout := func(i int) string { + return filepath.Join(dir, fmt.Sprintf("rollout-2026-09-30T10-00-0%d-s%d.jsonl", i, i)) + } + writeCodexCall(t, rollout(0), "main-a", "native-main", `"vscode"`, "resp-0", "m", "low", now.Add(-time.Minute), 60, 6) + for i := 1; i < 5; i++ { + at := now.Add(-time.Duration(i) * time.Hour) + if i%2 == 0 { + at = at.UTC() // a row's zone is kept as it was read + } + writeCodexCall(t, rollout(i), fmt.Sprintf("s%d", i), fmt.Sprintf("native-%d", i), `"cli"`, fmt.Sprintf("resp-%d", i), "m", "high", at, 10*i, i) + } + Append(Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 60, Output: 6, Status: 200, ResponseID: "resp-0"}) + + forget := func() { + requestDiskSaves.Wait() + requestCache.Lock() + requestCache.chunks = map[string]*rowChunk{} + requestCache.pages, requestCache.parts, requestCache.pairs, requestCache.heats = nil, nil, nil, nil + requestCache.key = "" + requestCache.Unlock() + sessions.Reset() + } + var reads atomic.Int32 + page := func() RequestPage { + t.Helper() + reads.Store(0) + got := queryPage(All, Filter{}, 0, 100, func(s sessions.CallSource) []sessions.Call { + reads.Add(1) + return sessions.ReadCallSource(s) + }) + equalPage(t, got, pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{}))) + return got + } + first := page() + // the identity's rollout is a session file too + all := reads.Load() + if first.Total != 5 || all != 6 { + t.Fatalf("first page: %d rows from %d reads, want 5 from 6", first.Total, all) + } + requestDiskSaves.Wait() + if _, err := os.Stat(requestDiskPath()); err != nil { + t.Fatalf("no file of the chunks: %v", err) + } + + forget() + equalPage(t, page(), first) + if n := reads.Load(); n != 0 { + t.Fatalf("a start read %d session files, want 0", n) + } + + // a file written over to the same size is read again for its mtime + writeCodexCall(t, rollout(1), "s1", "native-1", `"cli"`, "resp-1", "m", "high", now.Add(-time.Hour), 11, 1) + later := time.Now().Add(time.Minute) + if err := os.Chtimes(rollout(1), later, later); err != nil { + t.Fatal(err) + } + forget() + if p := page(); p.Sum.Input != first.Sum.Input+1 || reads.Load() != 1 { + t.Fatalf("a changed file: %d input from %d reads, want %d from 1", p.Sum.Input, reads.Load(), first.Sum.Input+1) + } + + // other prices: the file is of the old ones, and every file is read + requestDiskSaves.Wait() + os.WriteFile(catalog.CachePath(), []byte(`{"openai":{"id":"openai","models":{"m":{"id":"m","cost":{"input":20,"output":80,"cache_read":5,"cache_write":25}}}}}`), 0600) + catalog.Reset() + forget() + if p := page(); reads.Load() != all || p.Sum.Cost == first.Sum.Cost { + t.Fatalf("new prices: %d reads, cost %v (was %v), want %d reads at the new prices", reads.Load(), p.Sum.Cost, first.Sum.Cost, all) + } + + // a file cut short stands for the entries before the cut + requestDiskSaves.Wait() + b, err := os.ReadFile(requestDiskPath()) + if err != nil { + t.Fatal(err) + } + os.WriteFile(requestDiskPath(), b[:len(b)-3], 0600) + forget() + if page(); reads.Load() == 0 || reads.Load() == all { + t.Fatalf("a cut file: %d reads, want the cut entry's and fewer than %d", reads.Load(), all) + } + os.WriteFile(requestDiskPath(), []byte("garbage"), 0600) + forget() + if page(); reads.Load() != all { + t.Fatalf("a bad file: %d reads, want %d", reads.Load(), all) + } +} diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index e24195e32..f2f583beb 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -485,6 +485,12 @@ type requestIndex struct { // pairs are the last pairing of each of a few periods (pairMemo), // kept as parts are pairs map[Period]*pairMemo + // on are the paths the last read listed; unsaved counts the chunks + // made since the file of them was last written (toDisk), and saving + // says a write is under way + on map[string]bool + unsaved int + saving bool } // heatPage is a heatmap's page, of the gateway log's snapshot version, @@ -693,6 +699,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C if !shared.keep(idx, b.on) { return page } + shared.noteBuilt(b) if cache != nil { if shared.parts == nil || len(shared.parts) >= partSets && shared.parts[pk] == nil { shared.parts = map[partKey]map[uint64]*chunkPart{} @@ -738,6 +745,7 @@ func codexEffortOfIndex(st requestState, p Period, now time.Time) map[string][]s b.priced.release() shared.Lock() if shared.keep(idx, b.on) { + shared.noteBuilt(b) shared.trim(requestCacheBytes) } shared.Unlock() @@ -751,6 +759,8 @@ type requestBlocks struct { gateways, chunks, others []*rowChunk on map[string]bool priced *blockPricer + // built counts the session files' chunks made again + built int } // readRequestBlocks reads the blocks of p at now into idx, a private copy @@ -809,13 +819,24 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti on := map[string]bool{} var chunks []*rowChunk var resolver *sessionResolver - read := prefetchSources(sources, func(s sessions.CallSource) bool { + stale := func(s sessions.CallSource) bool { if !since.IsZero() && s.Modified.Before(since) { return false } c := idx.chunks[s.Path] return c == nil || c.Source.Size != s.Size || !c.Source.Modified.Equal(s.Modified) - }, readSource) + } + want := map[string]sessions.CallSource{} + for _, s := range sources { + if stale(s) { + want[s.Path] = s + } + } + if len(want) >= requestDiskLeast { + idx.fromDisk(want) + } + built := 0 + read := prefetchSources(sources, stale, readSource) for i, s := range sources { on[s.Path] = true if !since.IsZero() && s.Modified.Before(since) { @@ -843,6 +864,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti c.dict, c.shapeIDs = nil, nil // local chunks are immutable until the source changes c = c.pack() c.serial = nextChunkSerial() + built++ } kept, next := *c, *c kept.Used, next.Used = idx.tick, idx.tick @@ -892,7 +914,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti delete(idx.chunks, path) } } - return requestBlocks{gateways: gateways, chunks: chunks, others: others, on: on, priced: priced} + return requestBlocks{gateways: gateways, chunks: chunks, others: others, on: on, priced: priced, built: built} } // adopt drops what idx keeps of a state other than st: every chunk when @@ -945,6 +967,40 @@ func (idx *requestIndex) keep(read *requestIndex, on map[string]bool) bool { return true } +// noteBuilt counts the chunks b made, and writes the file of them once +// they are requestDiskLeast or more (a first read of the history): fewer +// are a few shard reads at the next start, and not worth writing the +// whole file (~44MB for 15.6k sessions) again. idx is locked. +func (idx *requestIndex) noteBuilt(b requestBlocks) { + idx.on = b.on + idx.unsaved += b.built + if idx.unsaved >= requestDiskLeast { + idx.save() + } +} + +// requestDiskSaves are the writes under way, for the tests to wait on. +var requestDiskSaves sync.WaitGroup + +// save writes the file of idx's chunks behind the lock: chunks are never +// changed once made, so a copy of the map is enough. idx is locked. +func (idx *requestIndex) save() { + if idx.saving { + return + } + idx.saving = true + idx.unsaved = 0 // a write that fails is tried again only for new chunks + root, meta, chunks, on := idx.root, idx.meta, maps.Clone(idx.chunks), idx.on + requestDiskSaves.Add(1) + go func() { + defer requestDiskSaves.Done() + _ = toDisk(root, meta, chunks, on) + idx.Lock() + defer idx.Unlock() + idx.saving = false + }() +} + // keepWhileAsked holds the chunks to requestCacheBytes while the page is // asked for, and to requestIdleBytes once it has gone unasked for // requestIdle. idx is locked. diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index a49384539..b4a268132 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -36,6 +36,21 @@ func (c *rowChunk) pack() *rowChunk { if c == nil || len(c.Rows) < 64 || len(c.Archive) != 0 { return c } + encoded, locations := c.encode(func(encoded []byte) bool { return int64(len(encoded)) < c.Bytes }) + if encoded == nil { + return c + } + next := *c + next.Count = len(c.Rows) // what rowsIn says of it + next.Rows, next.Strings, next.Shapes, next.dict, next.shapeIDs = nil, nil, nil, nil, nil + next.Archive, next.Locations = encoded, locations + next.Bytes = int64(len(next.Archive)+len(locations)*8) + codexActorBytes(next.codexActors) + return &next +} + +// encode is c's rows as an archive and the locations their times are in, +// or nil when keep turns the compressed bytes down. +func (c *rowChunk) encode(keep func([]byte) bool) ([]byte, []*time.Location) { scratch := rowEncodes.Get().(*[2][]byte) defer rowEncodes.Put(scratch) data := scratch[0][:0] @@ -87,15 +102,10 @@ func (c *rowChunk) pack() *rowChunk { } encoded := s2.Encode(scratch[1][:cap(scratch[1])], data) scratch[1] = encoded[:0] - if int64(len(encoded)) >= c.Bytes { - return c + if !keep(encoded) { + return nil, nil } - next := *c - next.Count = len(c.Rows) // what rowsIn says of it - next.Rows, next.Strings, next.Shapes, next.dict, next.shapeIDs = nil, nil, nil, nil, nil - next.Archive, next.Locations = slices.Clone(encoded), locations - next.Bytes = int64(len(next.Archive)+len(locations)*8) + codexActorBytes(next.codexActors) - return &next + return slices.Clone(encoded), locations } func (c *rowChunk) unpack() *rowChunk { return c.unpackInto(nil) }