diff --git a/internal/gui/api.go b/internal/gui/api.go index b6bd8814e..300afb21d 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1057,8 +1057,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { return } s := state() - writeJSON(rw, s) - keepState(s) + if sum, ok := writeStateJSON(rw, s); ok { + keepStateSummed(s, sum) + } }) mux.HandleFunc("POST /api/set", func(rw http.ResponseWriter, r *http.Request) { var in struct{ Agent, Field, Value string } diff --git a/internal/gui/laststate.go b/internal/gui/laststate.go index 5d3b2f1fb..c4ae10fee 100644 --- a/internal/gui/laststate.go +++ b/internal/gui/laststate.go @@ -71,14 +71,25 @@ func lastStatePath() string { return filepath.Join(appdir.Cache(), "agents-state // (edit.WriteAtomic's would: every poll of the Agents page rebuilt each // agent's model list and picker, and every provider's catalog, anew). func keepState(s stateJSON) { - s.Settings = settings.Settings{} - // and what is told once: a notice, a file recovered after a crash - s.Notice, s.Connected, s.Recovered = "", nil, nil - f := stateFile{Version: Version, State: s} - sum, err := encodedSum(f) + sum, err := encodedSum(keptFile(s)) if err != nil { return } + keepStateSummed(s, sum) +} + +// keptFile is what keepState keeps of s. +func keptFile(s stateJSON) stateFile { + s.Settings = settings.Settings{} + // and what is told once: a notice, a file recovered after a crash + s.Notice, s.Connected, s.Recovered = "", nil, nil + return stateFile{Version: Version, State: s} +} + +// keepStateSummed is keepState given sum, encodedSum(keptFile(s)), found +// while s was written (writeStateJSON). +func keepStateSummed(s stateJSON, sum [32]byte) { + f := keptFile(s) lastState.Lock() defer lastState.Unlock() if !lastState.read { diff --git a/internal/gui/statewrite.go b/internal/gui/statewrite.go new file mode 100644 index 000000000..18b8783ff --- /dev/null +++ b/internal/gui/statewrite.go @@ -0,0 +1,76 @@ +package gui + +import ( + "bufio" + "bytes" + "crypto/sha256" + "encoding/json" + "io" + "net/http" +) + +// agentsNull is how a stateJSON with no agents begins: Agents is its +// first field. +const agentsNull = `{"agents":null` + +// writeStateJSON writes s to rw as writeJSON does, and returns keepState's +// sum of it (encodedSum(keptFile(s))), encoding each agent once, for both. +// Encoding the state whole grew a buffer to its size, twice a poll: once +// to send it and once for the sum, 68 MB of what twenty polls of the +// Agents page allocated with real accounts. Each agent is encoded alone +// now, straight to both, and only the rest of the state, without its +// agents, is encoded twice (with the settings and without). false when +// the sum wasn't found; s was written all the same, when it could be. +func writeStateJSON(rw http.ResponseWriter, s stateJSON) ([32]byte, bool) { + agents := s.Agents + f := keptFile(s) + s.Agents, f.State.Agents = nil, nil + tail, err := json.Marshal(s) + keptTail, kerr := json.Marshal(f) + v, _ := json.Marshal(Version) + keptHead := `{"version":` + string(v) + `,"state":` + agentsNull + if agents == nil || err != nil || kerr != nil || + !bytes.HasPrefix(tail, []byte(agentsNull)) || !bytes.HasPrefix(keptTail, []byte(keptHead)) { + s.Agents = agents + writeJSON(rw, s) + sum, err := encodedSum(keptFile(s)) + return sum, err == nil + } + rw.Header().Set("Content-Type", "application/json") + out := bufio.NewWriterSize(rw, 32<<10) + defer out.Flush() + h := sha256.New() + _, _ = out.WriteString(`{"agents":[`) + h.Write([]byte(keptHead[:len(keptHead)-len("null")] + "[")) + // each agent goes straight to rw and the sum, as Encode writes it + enc := json.NewEncoder(lineless{io.MultiWriter(out, h)}) + for i := range agents { + if i > 0 { + _ = out.WriteByte(',') + h.Write([]byte{','}) + } + // a pointer, so a method on *T is used as it is in the slice + if enc.Encode(&agents[i]) != nil { + return [32]byte{}, false + } + } + _ = out.WriteByte(']') + _, _ = out.Write(tail[len(agentsNull):]) + _ = out.WriteByte('\n') + h.Write([]byte{']'}) + h.Write(keptTail[len(keptHead):]) + h.Write([]byte{'\n'}) + return [32]byte(h.Sum(nil)), true +} + +// lineless writes what a json.Encoder writes without the newline Encode +// ends each value with: Encode writes a value and its newline at once. +type lineless struct{ w io.Writer } + +func (l lineless) Write(b []byte) (int, error) { + if n := len(b); n > 0 && b[n-1] == '\n' { + _, err := l.w.Write(b[:n-1]) + return n, err + } + return l.w.Write(b) +} diff --git a/internal/gui/statewrite_test.go b/internal/gui/statewrite_test.go new file mode 100644 index 000000000..b1fdc1c12 --- /dev/null +++ b/internal/gui/statewrite_test.go @@ -0,0 +1,112 @@ +package gui + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "runtime" + "testing" + + "github.com/yetone/magpie/internal/agent" +) + +// sinkWriter is a ResponseWriter that keeps what is written, or only +// counts it. +type sinkWriter struct { + h http.Header + keep bool + body bytes.Buffer + n int +} + +func (w *sinkWriter) Header() http.Header { + if w.h == nil { + w.h = http.Header{} + } + return w.h +} +func (w *sinkWriter) WriteHeader(int) {} +func (w *sinkWriter) Write(b []byte) (int, error) { + w.n += len(b) + if w.keep { + w.body.Write(b) + } + return len(b), nil +} + +// bigState is a state the size real accounts give the Agents page: many +// agents, each with long model pickers. +func bigState() stateJSON { + var s stateJSON + for a := range 40 { + var opts []agent.Option + for m := range 300 { + opts = append(opts, agent.Option{ + Value: fmt.Sprintf("provider-%d/model-%d", a, m), + Label: fmt.Sprintf("Model %d & cheap", m), + Note: "200K context ยท $3/$15", + Group: "Provider", + }) + } + s.Agents = append(s.Agents, agentJSON{ + ID: fmt.Sprintf("agent-%d", a), Name: "Agent", Path: "/usr/local/bin/agent", + Fields: []fieldJSON{{Key: "model", Label: "Model", Value: "provider/model-1", Options: opts}}, + }) + } + s.Profiles = []profileJSON{{Name: "work", Summary: "Work"}} + s.Catalog = "ok" + s.Notice = "restart Codex" + s.Served = 12000 + return s +} + +// The state is written as writeJSON wrote it, and the sum it gives is the +// one keepState finds for it, with no agents too. +func TestStateWrittenAsEncoded(t *testing.T) { + for _, s := range []stateJSON{bigState(), {Agents: []agentJSON{}}, {}} { + w := &sinkWriter{keep: true} + sum, ok := writeStateJSON(w, s) + var want bytes.Buffer + if err := json.NewEncoder(&want).Encode(s); err != nil { + t.Fatal(err) + } + if !bytes.Equal(w.body.Bytes(), want.Bytes()) { + t.Fatalf("the state was written as\n%.300s\nwant\n%.300s", w.body.Bytes(), want.Bytes()) + } + kept, err := encodedSum(keptFile(s)) + if err != nil || !ok || sum != kept { + t.Fatalf("the sum found while writing (%v) is not keepState's", ok) + } + if ct := w.Header().Get("Content-Type"); ct != "application/json" { + t.Fatalf("Content-Type %q", ct) + } + } +} + +// Each poll of the Agents page encoded the state whole twice, to send it +// and for keepState's sum, growing a buffer to its size each time: 68 MB +// of what twenty polls allocated. Each agent is encoded once now, alone. +func TestStateWriteGrowsNoBufferItsSize(t *testing.T) { + s := bigState() + w := &sinkWriter{} + writeStateJSON(w, s) // json's encoders, warmed + size := w.n + const runs = 5 + var all uint64 + for range runs { + // polls are seconds apart, and a GC between them empties the + // buffers json pools (twice: a pool keeps a GC's victims once) + runtime.GC() + runtime.GC() + var m0, m1 runtime.MemStats + runtime.ReadMemStats(&m0) + writeStateJSON(&sinkWriter{}, s) + runtime.ReadMemStats(&m1) + all += m1.TotalAlloc - m0.TotalAlloc + } + per := int(all) / runs + if per > size/2 { + t.Fatalf("writing a %d-byte state allocated %d bytes, want under half its size", size, per) + } +}