diff --git a/internal/sessions/cache_decode.go b/internal/sessions/cache_decode.go index 49f2f25cf..682681a82 100644 --- a/internal/sessions/cache_decode.go +++ b/internal/sessions/cache_decode.go @@ -1,8 +1,12 @@ package sessions import ( + "bytes" "encoding/json" + "io" + "maps" "runtime" + "slices" "strings" "sync" "sync/atomic" @@ -73,6 +77,57 @@ func decodeCache(b []byte, zone string) (map[string]*state, bool) { 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"` + }{c.Version, c.Zone}); 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 +} + // share has st's strings that many files repeat held once: an agent run // by a script gives each of its sessions the same prompt, and a long // history's 23.7k copies of one ~420-byte title, with its cwds and model diff --git a/internal/sessions/cache_decode_test.go b/internal/sessions/cache_decode_test.go index a778adf15..38c2c84ed 100644 --- a/internal/sessions/cache_decode_test.go +++ b/internal/sessions/cache_decode_test.go @@ -1,11 +1,13 @@ package sessions import ( + "bytes" "encoding/json" "fmt" "reflect" "strings" "testing" + "time" "unsafe" ) @@ -91,3 +93,35 @@ func TestDecodeCacheSharesRepeats(t *testing.T) { t.Fatalf("file 3: %+v", st) } } + +// 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/.jsonl": {Size: 3, Mod: 9, Title: "a & \"c\" 
", Start: at, Last: at, Models: map[string]Tokens{"m": {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: "", Files: map[string]*state{}}, + {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:]) + } + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 54d5cb3dc..00b047431 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -15,7 +15,6 @@ import ( "bufio" "bytes" "cmp" - "encoding/json" "errors" "io" "io/fs" @@ -825,10 +824,6 @@ func writeCache(c *save) { if saveHook != nil { saveHook() } - b, err := json.Marshal(c.cacheFile) - if err != nil { - return - } dir := filepath.Dir(c.path) if os.MkdirAll(dir, 0o755) != nil { return @@ -837,7 +832,10 @@ func writeCache(c *save) { if err != nil { return } - _, err = tmp.Write(b) + w := bufio.NewWriterSize(tmp, 1<<20) + if err = encodeCache(w, c.cacheFile); err == nil { + err = w.Flush() + } if cerr := tmp.Close(); err == nil { err = cerr }