gui: a state poll encodes into buffers kept from the last one, and Codex's own models are read without a copy

Each /api/state poll json.Marshal'd the state without its agents twice
(to send it and for keepState's sum) into fresh slices, and made a new
32KB writer; ownCodex cloned Codex's whole model list for a caller that
only reads it. One set of buffers and the writer is now kept between
polls (an atomic slot, not a sync.Pool, which a GC between polls
empties; a poll that finds it taken makes its own, and buffers over
4MB are dropped), and ownCodex reads catalog.CodexShared.

Run on mote at this tree: go vet ./internal/gui ./internal/agent;
go test -run "State|Settings|Allow" ./internal/gui, the same -race for
StateWritten, -run "Codex|OwnCodex|Pick" ./internal/agent: ok.
TestStateWrittenAsEncoded now writes big after small and small after
big; with encodeTo's Reset taken out by hand it is red (a stale tail).
Real accounts, 40 polls of /api/state, alloc_space: 27.8 and 26.1 MB
before, 18.4 and 22.7 MB after.
Not tried: Windows and Linux runs (no OS-specific code).
This commit is contained in:
yetone
2026-11-10 09:23:47 +08:00
parent f90414f884
commit 1b078d404b
3 changed files with 51 additions and 6 deletions
+2 -2
View File
@@ -2565,12 +2565,12 @@ func codexEnableEfforts(path string, ms []catalog.Model) error {
// subscription in magpie when any are — the subscription switched off, its
// picks narrow nothing, as it serves no agent anything.
func ownCodex() []catalog.Model {
ms := catalog.Codex()
ms := catalog.CodexShared() // only read (codexNamed), on every poll
picks := codexPicks()
if len(picks) == 0 {
return ms
}
var out []catalog.Model
out := make([]catalog.Model, 0, min(len(picks), len(ms)))
for _, m := range ms {
if slices.Contains(picks, m.ID) {
out = append(out, m)
+47 -3
View File
@@ -7,8 +7,35 @@ import (
"encoding/json"
"io"
"net/http"
"sync/atomic"
)
// stateHeld is what writeStateJSON writes through, used again from poll
// to poll: two buffers for the state without its agents (which
// json.Marshal copied out whole each time) and the 32KB writer. One set
// is kept, not a sync.Pool's: polls are seconds apart and a GC between
// them would empty a pool. A poll that finds it taken makes its own.
var stateHeld atomic.Pointer[stateBufs]
type stateBufs struct {
tail, kept bytes.Buffer
out *bufio.Writer
}
// encodeTo is json.Marshal(v) into b, without its copy of the result:
// Encode escapes as Marshal does, and its newline is cut.
func encodeTo(b *bytes.Buffer, v any) ([]byte, error) {
b.Reset()
if err := json.NewEncoder(b).Encode(v); err != nil {
return nil, err
}
return bytes.TrimSuffix(b.Bytes(), []byte{'\n'}), nil
}
// stateBufMax is the largest buffer kept for the next poll; one grown
// past it by an odd state goes.
const stateBufMax = 4 << 20
// agentsNull is how a stateJSON with no agents begins: Agents is its
// first field.
const agentsNull = `{"agents":null`
@@ -25,8 +52,20 @@ 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)
bufs := stateHeld.Swap(nil)
if bufs == nil {
bufs = new(stateBufs)
}
defer func() {
if bufs.tail.Cap() <= stateBufMax && bufs.kept.Cap() <= stateBufMax {
if bufs.out != nil {
bufs.out.Reset(nil)
}
stateHeld.CompareAndSwap(nil, bufs)
}
}()
tail, err := encodeTo(&bufs.tail, s)
keptTail, kerr := encodeTo(&bufs.kept, f)
v, _ := json.Marshal(Version)
keptHead := `{"version":` + string(v) + `,"state":` + agentsNull
if agents == nil || err != nil || kerr != nil ||
@@ -37,7 +76,12 @@ func writeStateJSON(rw http.ResponseWriter, s stateJSON) ([32]byte, bool) {
return sum, err == nil
}
rw.Header().Set("Content-Type", "application/json")
out := bufio.NewWriterSize(rw, 32<<10)
if bufs.out == nil {
bufs.out = bufio.NewWriterSize(rw, 32<<10)
} else {
bufs.out.Reset(rw)
}
out := bufs.out
defer out.Flush()
h := sha256.New()
_, _ = out.WriteString(`{"agents":[`)
+2 -1
View File
@@ -64,7 +64,8 @@ func bigState() stateJSON {
// 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{}}, {}} {
// Big after small and small after big: the held buffers are used again.
for _, s := range []stateJSON{bigState(), {Agents: []agentJSON{}}, {}, bigState(), {}} {
w := &sinkWriter{keep: true}
sum, ok := writeStateJSON(w, s)
var want bytes.Buffer