sessions: sessions.json is written a file's parse at a time
A save marshalled the whole index into one buffer: 22.8MB for a long
history (15,624 files), grown by doubling to ~85MB of allocation a save,
and a save follows every refresh that read a changed session file, so a
start while agents run, and a Sessions or Usage poll after any call. It
is written through a json.Encoder into a 256KB buffer handed to a 1MB
bufio.Writer on the temp file, keys in json.Marshal's order and escaped
as it escapes them, so the file is the same bytes.
Measured on the real sessions.json (sbpairs, 22,836,803 bytes):
json.Marshal 54-73ms and 85MB alloc; encodeCache 51ms and 14MB alloc;
the output equal byte for byte.
Run at this tree (3767addd4 + the race skip + this change):
- go test -race -count=1 ./internal/sessions: ok
- go test -count=1 ./internal/sessions ./internal/usage ./internal/gui
./internal/agent/...: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions: ok;
gofmt -l clean
- TestEncodeCacheIsMarshal compares with json.Marshal for 3002 files (a
key and a title with <, &, quotes and U+2028, a file of no parse), an
empty index and none. Broken by hand (keys in map order): red; restored:
green.
Not tried: the save on Windows or Linux.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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/<a&b>.jsonl": {Size: 3, Mod: 9, Title: "a <b> & \"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: "<z>", 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:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user