sessions: the kept parses are written binary, not JSON

The Sessions and Usage index (sessions.json, ~18k files on a long
history) was JSON. Every start decoded all of it through reflection,
and every save, which happens at most once a minute while a session is
live, marshalled it whole again. It is now a compact binary form
(cache_binary.go):
- A magic and a version header.
- Then length-prefixed records, varints for the numbers.
- Interned names, as the JSON path interned them.
- The rare nested parts (Claude Code's window, a Codex identity,
  StateMore) as JSON blobs.
Records are decoded in parallel.

A JSON index from an older magpie is still read. loadCache saves it
again at once, so it turns binary on the first start even when no
session changed; before, a save came only after a file changed.

A binary file is refused whole, never half read: when it is cut
anywhere, has a byte added, or is of another zone or version. That
means one full read again, as a refused JSON file meant before.
TestCacheBinaryKnowsEveryField fails when state, day or Tokens gains a
field that the binary form doesn't carry.

On the real acctp history, on mote (18,346 files):
- The file is 14.8 MB, down from 23.3 MB.
- Decoding takes 19 ms, down from 69 ms, and allocates 28 MB, down
  from 58 MB.
- Encoding takes 10 ms, down from 98 ms, and allocates 3.1 MB, down
  from 32.5 MB.
- The heap kept after decoding is the same: 24 MB.
- /api/sessions from a w94 build on the binary index and from a w92
  build (before) on the JSON index answer the same bytes (5000
  sessions). Neither rewrote the index.
- The page-open footprint peak was 152 to 214 MB on both builds at
  load 60 to 80. It is too noisy to claim a change.

Run:
- mica-run go test -count=1 -timeout 45m ./internal/sessions
  ./internal/usage ./internal/gui: all ok.
- GOOS=linux and GOOS=windows go vet ./internal/sessions
  ./internal/usage: ok. go vet ./internal/sessions: ok.
- gofmt -l: clean.
- TestCacheBinaryRefusesBadFiles cuts the file at every length, adds a
  byte, changes the zone and the version, and flips every byte; it
  checks that a bad file is never accepted and never panics.

Broken by hand:
- The decoder skipped Provider: TestCacheBinaryIsJSON went red.
- loadCache stopped re-saving a JSON index:
  TestCacheJSONRewrittenOnStart went red, the file still JSON.

At the pushed head (rebased on 500f39886): go test ./internal/sessions
./internal/testenv ok.

Not tried: Windows and Linux runs of the package; the mapping read is
shared code and unchanged there.
This commit is contained in:
yetone
2026-11-16 02:58:09 +08:00
parent 500f39886e
commit ff6f6337f1
9 changed files with 802 additions and 128 deletions
+541
View File
@@ -0,0 +1,541 @@
package sessions
import (
"bytes"
"encoding/binary"
"encoding/json"
"io"
"maps"
"runtime"
"slices"
"sync"
"sync/atomic"
"time"
"unique"
)
// cacheMagic starts a kept file written in binary. The JSON one it
// replaced took json.Unmarshal 320 to 440ms of every start for a long
// history's 40MB, and json's reflection allocated ~20MB to encode it on
// each save; this form is a few times smaller and read and written without
// reflection. A file without it is the old JSON, read once and written
// back in this form; an older magpie finds this one invalid and reads its
// files again, as it would any file of another version.
const cacheMagic = "MGPSC\x01"
// what a kept state has, past its fixed fields (encodeState)
const (
stHead = 1 << iota
stContentHash
stCdRead
stTotal
stClaude
stCodexIdentity
stMore
)
// encodeCache writes c in the binary form, a file's parse at a time:
// a header (the magic, version, zone and parsers), the number of files,
// and each file's name and its state, the state's length first so the
// states can be read on several goroutines.
func encodeCache(w io.Writer, c cacheFile) error {
b := make([]byte, 0, 256<<10)
b = append(b, cacheMagic...)
b = binary.AppendUvarint(b, uint64(c.Version))
b = appendStr(b, c.Zone)
b = binary.AppendUvarint(b, uint64(len(c.Parsers)))
for _, k := range slices.Sorted(maps.Keys(c.Parsers)) {
b = appendStr(b, k)
b = binary.AppendVarint(b, int64(c.Parsers[k]))
}
if c.Files == nil {
b = append(b, 0) // no files at all, as JSON's null
_, err := w.Write(b)
return err
}
b = append(b, 1)
b = binary.AppendUvarint(b, uint64(len(c.Files)))
var rec []byte
for _, k := range slices.Sorted(maps.Keys(c.Files)) {
b = appendStr(b, k)
st := c.Files[k]
if st == nil {
b = append(b, 0)
} else {
var err error
if rec, err = st.appendBinary(rec[:0]); err != nil {
return err
}
b = binary.AppendUvarint(b, uint64(len(rec))+1)
b = append(b, rec...)
}
if len(b) >= 256<<10 {
if _, err := w.Write(b); err != nil {
return err
}
b = b[:0]
}
}
_, err := w.Write(b)
return err
}
func appendStr(b []byte, s string) []byte {
b = binary.AppendUvarint(b, uint64(len(s)))
return append(b, s...)
}
func appendTokens(b []byte, t Tokens) []byte {
b = binary.AppendVarint(b, int64(t.Input))
b = binary.AppendVarint(b, int64(t.Output))
b = binary.AppendVarint(b, int64(t.CacheRead))
b = binary.AppendVarint(b, int64(t.CacheWrite))
return binary.AppendVarint(b, int64(t.CacheWrite1h))
}
// appendTime is t, as time's own binary form (its instant and offset),
// or a 0 for the zero time.
func appendTime(b []byte, t time.Time) ([]byte, error) {
if t == (time.Time{}) {
return append(b, 0), nil
}
n := len(b)
b = append(b, 0)
b, err := t.AppendBinary(b)
if err != nil {
return nil, err
}
b[n] = byte(len(b) - n - 1)
return b, nil
}
func appendNamedTokens(b []byte, n named[Tokens]) []byte {
b = binary.AppendUvarint(b, uint64(len(n)))
for _, e := range n {
b = appendStr(b, e.name)
b = appendTokens(b, e.v)
}
return b
}
func appendNamedInt(b []byte, n named[int]) []byte {
b = binary.AppendUvarint(b, uint64(len(n)))
for _, e := range n {
b = appendStr(b, e.name)
b = binary.AppendVarint(b, int64(e.v))
}
return b
}
// appendJSON is v as JSON, its length first: what few states have
// (Claude Code's revision window, a Codex identity, StateMore) is kept as
// json.Marshal has it, and read back by json.Unmarshal.
func appendJSON(b []byte, v any) ([]byte, error) {
j, err := json.Marshal(v)
if err != nil {
return nil, err
}
b = binary.AppendUvarint(b, uint64(len(j)))
return append(b, j...), nil
}
// appendBinary is st in the binary form. Every field the JSON form kept is
// here (TestCacheBinaryKnowsEveryField).
func (st *state) appendBinary(b []byte) ([]byte, error) {
var flags uint64
if st.Head != (digest{}) {
flags |= stHead
}
if st.ContentHash != (digest{}) {
flags |= stContentHash
}
if st.CdRead {
flags |= stCdRead
}
if st.Total != nil {
flags |= stTotal
}
if st.Claude != nil {
flags |= stClaude
}
if st.CodexIdentity != nil {
flags |= stCodexIdentity
}
if st.StateMore != nil {
flags |= stMore
}
b = binary.AppendUvarint(b, flags)
b = appendStr(b, st.Agent)
if flags&stHead != 0 {
b = append(b, st.Head[:]...)
}
b = binary.AppendVarint(b, int64(st.HeadSize))
if flags&stContentHash != 0 {
b = append(b, st.ContentHash[:]...)
}
b = binary.AppendVarint(b, st.Size)
b = binary.AppendVarint(b, st.Mod)
b = binary.AppendVarint(b, st.Off)
b = appendStr(b, st.ID)
b = appendStr(b, st.Cwd)
b = appendStr(b, st.Title)
var err error
if b, err = appendTime(b, st.Start); err != nil {
return nil, err
}
if b, err = appendTime(b, st.Last); err != nil {
return nil, err
}
b = appendNamedTokens(b, st.Models)
b = binary.AppendUvarint(b, uint64(len(st.Days)))
for _, e := range st.Days {
b = appendStr(b, e.name)
d := e.v
if d == nil {
b = append(b, 0)
continue
}
b = append(b, 1)
b = appendNamedTokens(b, d.Models)
b = binary.AppendVarint(b, d.Active)
b = binary.AppendUvarint(b, uint64(len(d.Hours)))
for _, h := range d.Hours {
b = binary.AppendUvarint(b, h)
}
b = binary.AppendVarint(b, int64(d.Prompts))
b = binary.AppendVarint(b, int64(d.Replies))
b = appendNamedInt(b, d.Tools)
b = appendNamedInt(b, d.Skills)
}
b = appendStr(b, st.Entry)
b = appendStr(b, st.Msg)
b = appendStr(b, st.MsgModel)
b = appendTokens(b, st.MsgUse)
b = appendStr(b, st.MsgDay)
b = appendStr(b, st.Model)
if st.Total != nil {
b = appendTokens(b, *st.Total)
}
b = appendStr(b, st.Provider)
if st.Claude != nil {
if b, err = appendJSON(b, st.Claude); err != nil {
return nil, err
}
}
if st.CodexIdentity != nil {
if b, err = appendJSON(b, st.CodexIdentity); err != nil {
return nil, err
}
}
if st.StateMore != nil {
if b, err = appendJSON(b, st.StateMore); err != nil {
return nil, err
}
}
return b, nil
}
// reader reads the binary form; a read past its end, or of a number that
// isn't one, leaves it bad and every later read empty.
type reader struct {
b []byte
bad bool
}
func (r *reader) fail() { r.bad, r.b = true, nil }
func (r *reader) uvarint() uint64 {
v, n := binary.Uvarint(r.b)
if n <= 0 {
r.fail()
return 0
}
r.b = r.b[n:]
return v
}
func (r *reader) varint() int64 {
v, n := binary.Varint(r.b)
if n <= 0 {
r.fail()
return 0
}
r.b = r.b[n:]
return v
}
func (r *reader) int() int { return int(r.varint()) }
func (r *reader) take(n uint64) []byte {
if n > uint64(len(r.b)) {
r.fail()
return nil
}
out := r.b[:n]
r.b = r.b[n:]
return out
}
func (r *reader) byte() byte {
if b := r.take(1); len(b) == 1 {
return b[0]
}
return 0
}
// str is a copy of a string read: the bytes read are the mapped file's.
func (r *reader) str() string { return string(r.take(r.uvarint())) }
// name is a string many states repeat, held once (unique).
func (r *reader) name() string {
b := r.take(r.uvarint())
if len(b) == 0 {
return ""
}
return unique.Make(string(b)).Value()
}
// count is a number of things to read, each at least a byte long: more
// than are left is a bad file, not a large allocation.
func (r *reader) count() int {
n := r.uvarint()
if n > uint64(len(r.b)) {
r.fail()
return 0
}
return int(n)
}
func (r *reader) tokens() Tokens {
return Tokens{Input: r.int(), Output: r.int(), CacheRead: r.int(), CacheWrite: r.int(), CacheWrite1h: r.int()}
}
func (r *reader) time() time.Time {
n := r.byte()
if n == 0 {
return time.Time{}
}
var t time.Time
if t.UnmarshalBinary(r.take(uint64(n))) != nil {
r.fail()
}
return t
}
// sorted is whether name comes after the last entry's: a named is kept in
// its names' order, which find's binary search needs.
func sorted[V any](n named[V], name string) bool {
return len(n) == 0 || n[len(n)-1].name < name
}
func (r *reader) namedTokens() named[Tokens] {
k := r.count()
if k == 0 {
return nil
}
n := make(named[Tokens], 0, k)
for range k {
name := r.name()
if !sorted(n, name) {
r.fail()
}
n = append(n, entry[Tokens]{name, r.tokens()})
if r.bad {
return nil
}
}
return n
}
func (r *reader) namedInt() named[int] {
k := r.count()
if k == 0 {
return nil
}
n := make(named[int], 0, k)
for range k {
name := r.name()
if !sorted(n, name) {
r.fail()
}
n = append(n, entry[int]{name, r.int()})
if r.bad {
return nil
}
}
return n
}
// json reads a value appendJSON wrote into v.
func (r *reader) json(v any) {
j := r.take(r.uvarint())
if r.bad || json.Unmarshal(j, v) != nil {
r.fail()
}
}
// state reads what appendBinary wrote, and fails on anything left over.
func (r *reader) state() *state {
st := &state{}
flags := r.uvarint()
st.Agent = r.name()
if flags&stHead != 0 {
copy(st.Head[:], r.take(uint64(len(st.Head))))
}
st.HeadSize = int32(r.varint())
st.CdRead = flags&stCdRead != 0
if flags&stContentHash != 0 {
copy(st.ContentHash[:], r.take(uint64(len(st.ContentHash))))
}
st.Size, st.Mod, st.Off = r.varint(), r.varint(), r.varint()
st.ID = r.str()
st.Cwd = r.name()
st.Title = r.name()
st.Start, st.Last = r.time(), r.time()
st.Models = r.namedTokens()
if k := r.count(); k > 0 {
st.Days = make(named[*day], 0, k)
for range k {
name := r.name()
if !sorted(st.Days, name) {
r.fail()
}
var d *day
if r.byte() == 1 {
d = &day{Models: r.namedTokens(), Active: r.varint()}
if h := r.count(); h > 0 {
d.Hours = make(hours, h)
for i := range d.Hours {
d.Hours[i] = r.uvarint()
}
}
d.Prompts, d.Replies = r.int(), r.int()
d.Tools, d.Skills = r.namedInt(), r.namedInt()
}
if r.bad {
return nil
}
st.Days = append(st.Days, entry[*day]{name, d})
}
}
st.Entry = r.name()
st.Msg = r.str()
st.MsgModel = r.name()
st.MsgUse = r.tokens()
st.MsgDay = r.name()
st.Model = r.name()
if flags&stTotal != 0 {
t := r.tokens()
st.Total = &t
}
st.Provider = r.name()
if flags&stClaude != 0 {
r.json(&st.Claude)
}
if flags&stCodexIdentity != 0 {
r.json(&st.CodexIdentity)
}
if flags&stMore != 0 {
r.json(&st.StateMore)
}
if flags >= stMore<<1 || len(r.b) > 0 {
r.fail()
}
if r.bad {
return nil
}
st.share()
return st
}
// decodeCacheBinary is decodeCache of a file in the binary form.
func decodeCacheBinary(b []byte, zone string) (map[string]*state, bool) {
c, ok := readCacheBinary(b)
if !ok || c.Version != cacheVersion || c.Zone != zone || c.Files == nil {
return nil, false
}
return keepCurrent(c.Files, c.Parsers), true
}
// readCacheBinary is the kept file b in the binary form as it was written,
// its states read on a few goroutines; false when it doesn't read whole.
func readCacheBinary(b []byte) (cacheFile, bool) {
var c cacheFile
r := reader{b: b[len(cacheMagic):]}
c.Version = int(r.uvarint())
c.Zone = r.str()
c.Parsers = map[string]int{}
for range r.count() {
k := r.str()
c.Parsers[k] = int(r.varint())
}
switch r.byte() {
case 0:
return c, !r.bad && len(r.b) == 0
case 1:
default:
return c, false
}
n := r.count()
keys := make([]string, 0, n)
recs := make([][]byte, 0, n)
for range n {
keys = append(keys, r.str())
size := r.uvarint()
if size == 0 {
recs = append(recs, nil)
} else {
recs = append(recs, r.take(size-1))
}
if r.bad {
return c, false
}
}
if r.bad || len(r.b) > 0 {
return c, false
}
parsed := make([]*state, len(recs))
var bad atomic.Bool
one := func(i int) {
if recs[i] == nil {
return
}
rr := reader{b: recs[i]}
if parsed[i] = rr.state(); parsed[i] == nil {
bad.Store(true)
}
}
if workers := min(runtime.GOMAXPROCS(0), 8, len(recs)/1024); workers < 2 {
for i := range recs {
one(i)
}
} else {
var next atomic.Int64
var wg sync.WaitGroup
for range workers {
wg.Go(func() {
for {
i := int(next.Add(256)) - 256
if i >= len(recs) || bad.Load() {
return
}
for j := i; j < min(i+256, len(recs)); j++ {
one(j)
}
}
})
}
wg.Wait()
}
if bad.Load() {
return c, false
}
c.Files = make(map[string]*state, len(keys))
for i, k := range keys {
c.Files[k] = parsed[i]
}
return c, true
}
// isBinaryCache: b is a kept file in the binary form.
func isBinaryCache(b []byte) bool { return bytes.HasPrefix(b, []byte(cacheMagic)) }
+210
View File
@@ -0,0 +1,210 @@
package sessions
import (
"bytes"
"encoding/json"
"fmt"
"os"
"reflect"
"slices"
"strings"
"testing"
"time"
)
// richCache is a kept index with every field of a state, a day and Tokens
// set somewhere, and the rare parts (Claude Code's window, a Codex
// identity, StateMore) on some files.
func richCache(t *testing.T) cacheFile {
t.Helper()
var claude *claudeUsageState
if err := json.Unmarshal([]byte(`[{"key":"message:1","m":{"request":"r1","usage":{"at":"2026-10-24T01:02:03Z","model":"m","input":3},"call":2}}]`), &claude); err != nil {
t.Fatal(err)
}
at := time.Date(2026, 10, 24, 1, 2, 3, 4, time.UTC)
east := time.Date(2026, 10, 24, 9, 0, 0, 0, time.FixedZone("", 8*3600))
tok := Tokens{Input: 1, Output: -2, CacheRead: 3, CacheWrite: 1 << 40, CacheWrite1h: 5}
full := &state{
Agent: "claude", Claude: claude, Head: digest{1, 2, 3}, HeadSize: 4096, CdRead: true, ContentHash: digest{9: 7},
Size: 1 << 33, Mod: -5, Off: 77, ID: "id-1", CodexIdentity: &CodexIdentity{ID: "c", Role: "subagent", ParentSession: "p", RootSession: "r"},
Cwd: "/w/é", Title: "a <b> & \"c\" \x00", Start: at, Last: east,
Models: named[Tokens]{{"a", tok}, {"b", Tokens{}}},
Days: named[*day]{
{"2026-10-23", nil},
{"2026-10-24", &day{Models: named[Tokens]{{"a", tok}}, Active: 99, Hours: hours{hourEntry(3, 5), hourEntry(23, 1)}, Prompts: 2, Replies: 3,
Tools: named[int]{{"Bash", 4}, {"Read", 1}}, Skills: named[int]{{"pdf", 1}}}},
{"2026-10-25", &day{}},
},
Entry: "claude-desktop", Msg: "msg_1", MsgModel: "m", MsgUse: tok, MsgDay: "2026-10-24", Model: "gpt-5.5", Total: &Tokens{Input: 8},
Provider: "openai",
StateMore: &StateMore{DBRevision: "rev", Named: "n", Convs: []string{"c1"}, Since: at, CodexSpawnNames: map[string]string{"a": "b"}},
}
files := map[string]*state{"/full": full, "/nil": nil, "/empty": {}, "/k\x00e\"y": {Agent: "codex", Size: 1}}
for i := range 3000 {
files[fmt.Sprintf("/s/%04d.jsonl", i)] = &state{Size: int64(i), Cwd: strings.Repeat("d", i%300), Title: "t", Start: at, Last: at.Add(time.Duration(i) * time.Second),
Models: named[Tokens]{{"m", Tokens{Input: i}}}, Days: named[*day]{{"2026-10-24", &day{Models: named[Tokens]{{"m", Tokens{Input: i}}}}}}}
}
return cacheFile{Version: cacheVersion, Zone: "z", Parsers: map[string]int{}, Files: files}
}
// What the binary form reads back is what the JSON form it replaced read
// back, field for field.
func TestCacheBinaryIsJSON(t *testing.T) {
unraised(t)
for _, c := range []cacheFile{
richCache(t),
{Version: cacheVersion, Zone: "z", Files: map[string]*state{}},
{Version: cacheVersion, Zone: "z"},
} {
j, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
want, wantOK := decodeCache(j, "z")
var b bytes.Buffer
if err := encodeCache(&b, c); err != nil {
t.Fatal(err)
}
if !isBinaryCache(b.Bytes()) || b.Len() >= len(j) {
t.Fatalf("binary %d bytes, JSON %d", b.Len(), len(j))
}
got, ok := decodeCache(b.Bytes(), "z")
if ok != wantOK || !reflect.DeepEqual(got, want) {
gj, _ := json.Marshal(got)
wj, _ := json.Marshal(want)
t.Fatalf("%d files: got %v %.400s, want %v %.400s", len(c.Files), ok, gj, wantOK, wj)
}
if f := got["/full"]; f != nil && (f.Last.Location().String() != want["/full"].Last.Location().String() || !f.Last.Equal(want["/full"].Last)) {
t.Fatalf("last %v, want %v", f.Last, want["/full"].Last)
}
}
}
// A kept file cut anywhere, with a byte added, of another version or zone
// is refused, never half read and never a panic.
func TestCacheBinaryRefusesBadFiles(t *testing.T) {
unraised(t)
small := cacheFile{Version: cacheVersion, Zone: "z", Files: map[string]*state{}}
for k, v := range richCache(t).Files {
if !strings.HasPrefix(k, "/s/") {
small.Files[k] = v
}
}
var b bytes.Buffer
if err := encodeCache(&b, small); err != nil {
t.Fatal(err)
}
all := b.Bytes()
if files, ok := decodeCache(all, "z"); !ok || len(files) != len(small.Files) {
t.Fatalf("whole file: %d files, %v", len(files), ok)
}
for n := len(cacheMagic); n < len(all); n++ {
if files, ok := decodeCache(all[:n], "z"); ok {
t.Fatalf("cut at %d of %d: read %d files", n, len(all), len(files))
}
}
if _, ok := decodeCache(append(slices.Clip(all), 0), "z"); ok {
t.Fatal("a byte added was read")
}
if _, ok := decodeCache(all, "y"); ok {
t.Fatal("another zone was read")
}
small.Version--
b.Reset()
encodeCache(&b, small)
if _, ok := decodeCache(b.Bytes(), "z"); ok {
t.Fatal("another version was read")
}
// every byte flipped in turn: refused or read, never a panic
for i := len(cacheMagic); i < len(all); i++ {
bad := slices.Clone(all)
bad[i] ^= 0xff
decodeCache(bad, "z")
}
}
// Every field of a state the JSON form kept is in the binary form: a new
// field fails here until appendBinary and reader.state carry it.
func TestCacheBinaryKnowsEveryField(t *testing.T) {
fields := func(v any) []string {
var out []string
ty := reflect.TypeOf(v)
for i := range ty.NumField() {
out = append(out, ty.Field(i).Name)
}
return out
}
for _, c := range []struct {
v any
want []string
}{
{state{}, []string{"Agent", "Codex", "parsePath", "Claude", "Head", "HeadSize", "CdRead", "ContentHash", "Size", "Mod", "Off", "ID", "CodexIdentity", "Cwd", "Title", "Start", "Last", "Models", "Days", "Entry", "Msg", "MsgModel", "MsgUse", "MsgDay", "Model", "Total", "Provider", "StateMore"}},
{day{}, []string{"Models", "Active", "Hours", "Prompts", "Replies", "Tools", "Skills"}},
{Tokens{}, []string{"Input", "Output", "CacheRead", "CacheWrite", "CacheWrite1h"}},
} {
if got := fields(c.v); !slices.Equal(got, c.want) {
t.Errorf("%T has fields %v; the binary cache (cache_binary.go) carries %v: add the new one there and here", c.v, got, c.want)
}
}
}
// A JSON index an older magpie kept is read, and the next save writes it
// in the binary form.
func TestCacheJSONReadThenBinary(t *testing.T) {
unraised(t)
c := richCache(t)
j, _ := json.Marshal(c)
files, ok := decodeCache(j, "z")
if !ok || len(files) != len(c.Files) {
t.Fatalf("JSON: %d files, %v", len(files), ok)
}
var b bytes.Buffer
if err := encodeCache(&b, cacheFile{Version: cacheVersion, Zone: "z", Files: files}); err != nil {
t.Fatal(err)
}
again, ok := decodeCache(b.Bytes(), "z")
if !ok || !reflect.DeepEqual(again, files) {
t.Fatal("the JSON index written in binary reads back otherwise")
}
}
// savedIndex is the index on disk as it was saved, every file in it.
func savedIndex(t *testing.T) cacheFile {
t.Helper()
b, err := os.ReadFile(CachePath())
if err != nil {
t.Fatal(err)
}
c, ok := readCacheBinary(b)
if !isBinaryCache(b) || !ok {
t.Fatalf("cache file: %.200q", b)
}
return c
}
// An older magpie's JSON index, with no session changed since, is written
// again in the binary form on the first start: a save comes only when a
// file changes, so it stayed JSON, read the slow way on every start.
func TestCacheJSONRewrittenOnStart(t *testing.T) {
setup(t)
unraised(t)
List(0)
Saved()
c := savedIndex(t)
if len(c.Files) == 0 {
t.Fatal("the fixture keeps no parse: it tests nothing")
}
b, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(CachePath(), b, 0o644); err != nil {
t.Fatal(err)
}
Reset()
List(0)
Saved()
if again := savedIndex(t); len(again.Files) != len(c.Files) {
t.Fatalf("rewritten with %d files, want %d", len(again.Files), len(c.Files))
}
}
+21 -66
View File
@@ -1,10 +1,7 @@
package sessions
import (
"bytes"
"encoding/json"
"io"
"maps"
"runtime"
"slices"
"strings"
@@ -16,11 +13,15 @@ import (
"github.com/tidwall/gjson"
)
// decodeCache is the kept file b as json.Unmarshal reads it, with the files
// decodeCache is the kept file b, in the binary form (cache_binary.go) or
// as json.Unmarshal reads the JSON one an older magpie wrote, with the files
// decoded on a few goroutines: one Unmarshal of a long history's 40MB took
// 320 to 440ms of every start (#3493). False when b isn't valid JSON, is of
// another version or zone, or a file's parse doesn't decode.
func decodeCache(b []byte, zone string) (map[string]*state, bool) {
if isBinaryCache(b) {
return decodeCacheBinary(b, zone)
}
if !gjson.ValidBytes(b) {
return nil, false
}
@@ -35,14 +36,6 @@ func decodeCache(b []byte, zone string) (map[string]*state, bool) {
was[k.String()] = int(v.Int())
return true
})
// a parse of no named agent stands only when no agent's version moved
unnamed := true
for a, v := range was {
unnamed = unnamed && parseVersions[a] == v
}
for a, v := range parseVersions {
unnamed = unnamed && was[a] == v
}
var keys, raws []string
head[2].ForEach(func(k, v gjson.Result) bool {
keys = append(keys, strings.Clone(k.String()))
@@ -87,65 +80,27 @@ func decodeCache(b []byte, zone string) (map[string]*state, bool) {
for i, k := range keys {
files[k] = parsed[i] // a key given twice is its last, as Unmarshal has it
}
return keepCurrent(files, was), true
}
// keepCurrent is files without the parses made by another version of
// their agent's parser than parseVersions, which are read again; was is
// parseVersions as files were kept.
func keepCurrent(files map[string]*state, was map[string]int) map[string]*state {
// a parse of no named agent stands only when no agent's version moved
unnamed := true
for a, v := range was {
unnamed = unnamed && parseVersions[a] == v
}
for a, v := range parseVersions {
unnamed = unnamed && was[a] == v
}
for k, p := range files {
// made by another version of its agent's parser: read again
if p != nil && (p.Agent == "" && !unnamed || p.Agent != "" && was[p.Agent] != parseVersions[p.Agent]) {
delete(files, k)
}
}
return files, true
}
// encodeCache writes c as json.Marshal does, a file's parse at a time: one
// Marshal of a long history's 23MB grew its buffer to twice that, ~85MB a
// save, and a save follows every refresh that read a changed file.
func encodeCache(w io.Writer, c cacheFile) error {
var b bytes.Buffer
enc := json.NewEncoder(&b)
// put appends v as Marshal has it: Encode ends it with a newline
put := func(v any) error {
if err := enc.Encode(v); err != nil {
return err
}
b.Truncate(b.Len() - 1)
return nil
}
if err := put(struct {
Version int `json:"version"`
Zone string `json:"zone"`
Parsers map[string]int `json:"parsers,omitempty"`
}{c.Version, c.Zone, c.Parsers}); err != nil {
return err
}
b.Truncate(b.Len() - 1)
b.WriteString(`,"files":`)
if c.Files == nil {
b.WriteString("null}")
_, err := w.Write(b.Bytes())
return err
}
b.WriteByte('{')
for i, k := range slices.Sorted(maps.Keys(c.Files)) {
if i > 0 {
b.WriteByte(',')
}
if err := put(k); err != nil {
return err
}
b.WriteByte(':')
if err := put(c.Files[k]); err != nil {
return err
}
if b.Len() >= 256<<10 {
if _, err := w.Write(b.Bytes()); err != nil {
return err
}
b.Reset()
}
}
b.WriteString("}}")
_, err := w.Write(b.Bytes())
return err
return files
}
// share has st's strings that many files repeat held once: an agent run
+9 -34
View File
@@ -9,7 +9,6 @@ import (
"slices"
"strings"
"testing"
"time"
"unsafe"
)
@@ -141,38 +140,6 @@ func TestDecodeCacheSharesOneDaysModels(t *testing.T) {
}
}
// A save writes the file json.Marshal would, byte for byte, a file's parse
// at a time: keys in order and escaped as Marshal escapes them, a file of
// no parse, an empty index and none at all.
func TestEncodeCacheIsMarshal(t *testing.T) {
at := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC)
files := map[string]*state{"/b/<a&b>.jsonl": {Size: 3, Mod: 9, Title: "a <b> & \"c\" 
", Start: at, Last: at, Models: named[Tokens]{{"m", Tokens{Input: 1}}}}, "/a/x.jsonl": nil}
for i := range 3000 {
files[fmt.Sprintf("/s/%04d.jsonl", i)] = &state{Size: int64(i), Cwd: strings.Repeat("d", i%300), Start: at, Last: at.Add(time.Duration(i) * time.Second)}
}
for _, c := range []cacheFile{
{Version: cacheVersion, Zone: "28800/28800", Files: files},
{Version: cacheVersion, Zone: "<z>", Parsers: map[string]int{"codex": 2, "claude": 1}, Files: map[string]*state{"/c": {Agent: "codex", Size: 1}}},
{Version: cacheVersion, Zone: "0/0"},
} {
want, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
var got bytes.Buffer
if err := encodeCache(&got, c); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got.Bytes(), want) {
n := 0
for n < min(got.Len(), len(want)) && got.Bytes()[n] == want[n] {
n++
}
t.Fatalf("%d files: %d bytes, want %d; apart at %d: %.80q", len(c.Files), got.Len(), len(want), n, got.Bytes()[n:])
}
}
}
// A raise of one agent's parseVersions reads that agent's files again and
// keeps every other agent's parses: a raise of cacheVersion read a long
// history whole, minutes of CPU after an update (#2278).
@@ -183,11 +150,19 @@ func TestParseVersionsReadOneAgentAgain(t *testing.T) {
if err := encodeCache(&b, c); err != nil {
t.Fatal(err)
}
j, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
parseVersions = now
files, ok := decodeCache(b.Bytes(), "z")
if !ok {
fromJSON, jok := decodeCache(j, "z")
if !ok || !jok {
t.Fatal("refused")
}
if got := slices.Sorted(maps.Keys(fromJSON)); !slices.Equal(got, slices.Sorted(maps.Keys(files))) {
t.Fatalf("JSON kept %v, binary %v", got, slices.Sorted(maps.Keys(files)))
}
return slices.Sorted(maps.Keys(files))
}
files := map[string]*state{"/codex": {Agent: "codex", Size: 1}, "/claude": {Agent: "claude", Size: 2}, "/old": {Size: 3}}
+8 -7
View File
@@ -2,7 +2,6 @@ package sessions
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
@@ -27,14 +26,16 @@ func TestQoderUsageAfterWindowLoss(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var c map[string]any
dec := json.NewDecoder(bytes.NewReader(b))
dec.UseNumber()
if err := dec.Decode(&c); err != nil {
files, ok := decodeCache(b, zone())
if !ok || files[path] == nil {
t.Fatalf("cache file: %q", b)
}
files[path].Claude = nil
var w bytes.Buffer
if err := encodeCache(&w, cacheFile{Version: cacheVersion, Zone: zone(), Parsers: parseVersions, Files: files}); err != nil {
t.Fatal(err)
}
delete(c["files"].(map[string]any)[path].(map[string]any), "claude")
b, _ = json.Marshal(c)
b = w.Bytes()
if err := os.WriteFile(CachePath(), b, 0o644); err != nil {
t.Fatal(err)
}
+3 -9
View File
@@ -42,14 +42,7 @@ func TestParseVersionRaiseReadsThatAgentAlone(t *testing.T) {
}
// as an older magpie left it: no agent named, no versions
b, err := os.ReadFile(CachePath())
if err != nil {
t.Fatal(err)
}
var c cacheFile
if err := json.Unmarshal(b, &c); err != nil {
t.Fatal(err)
}
c := savedIndex(t)
for _, s := range c.Files {
if s != nil {
if s.Agent == "" {
@@ -59,7 +52,8 @@ func TestParseVersionRaiseReadsThatAgentAlone(t *testing.T) {
}
}
c.Parsers = nil
if b, err = json.Marshal(c); err != nil {
b, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(CachePath(), b, 0o644); err != nil {
+2 -9
View File
@@ -1,8 +1,6 @@
package sessions
import (
"encoding/json"
"os"
"sync"
"testing"
"time"
@@ -43,12 +41,7 @@ func TestSaveBehindTheRead(t *testing.T) {
// the save lands once let go, and a new load waits for it
let()
Saved()
b, err := os.ReadFile(CachePath())
if err != nil {
t.Fatal(err)
}
var kept cacheFile
if json.Unmarshal(b, &kept) != nil || len(kept.Files) == 0 {
t.Fatalf("cache file: %.200s", b)
if kept := savedIndex(t); len(kept.Files) == 0 {
t.Fatal("no files kept")
}
}
+6
View File
@@ -1514,9 +1514,15 @@ func loadCache() {
saved() // the kept file as the last save left it
if b, done, err := readCacheFile(CachePath()); err == nil {
files, ok := decodeCache(b, z)
old := !isBinaryCache(b)
done()
if ok {
cache = files
if old {
// an older magpie's JSON: written again in the binary
// form, or it stays JSON until a file changes
saveCache()
}
}
}
}
+2 -3
View File
@@ -187,9 +187,8 @@ func TestIncremental(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var kept cacheFile
if json.Unmarshal(b, &kept) != nil || kept.Version != cacheVersion || kept.Files[path] == nil {
t.Fatalf("cache file: %s", b)
if kept, ok := decodeCache(b, zone()); !ok || kept[path] == nil {
t.Fatalf("cache file: %q", b)
}
fi, _ := os.Stat(path)
raw, _ := os.ReadFile(path)