gui: a Providers poll sums what it keeps while writing the answer

Each poll of /api/providers encoded the answer for the page and then
encoded the kept last-known list again only to sum it (keepProviders,
encodedSum): 32-34 MB of what forty polls allocated with real accounts.

writeProvidersJSON now returns the encodedSum of keptProviders(s), taken
from the same encoding, as writeStateJSON does for /api/state. A row
kept as it is (no headers, proxy, extra body or account proxies) is
encoded once into the answer and the sum; only a row with those is
encoded again without them. The head and tail of the kept file come
from marshaling it with no rows. A nil row list, or a head that doesn't
match, falls back to the old writeJSON and encodedSum. The other
keepProviders callers (after a save) are unchanged.

Run on mote at this tree:
- gofmt, go vet ./internal/gui, GOOS=windows go vet -tags nogui: ok.
- go test -run 'Providers|Kept' ./internal/gui 3 times alone: ok.
- New TestProvidersWriteSumsWhatIsKept: the sum equals
  encodedSum(keptProviders(s)) for bigProviders, rows with each secret
  field, gateway calls, moved models, and empty and nil lists. Broken
  by hand twice: keepsAllOf always true (secrets summed) and the kept
  tail left out of the sum. Red both times.
- go test ./internal/gui: only the known reds,
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestMainWindowCorners (#3949).
- -race -run 'Providers|Kept': TestProvidersWriteGrowsNoBufferItsSize
  red, and red the same way at the base (c76bcaea7, twice): an
  allocation count under -race, where sync.Pool drops items. Fixed in
  its own commit next.

Real accounts, sandbox HOME, 40 polls of state, providers and drift,
v0.1.2509 (msteady) vs this (mpsum), two rounds each:
- alloc_space shown: 365.6/364.3 MB -> 341.5/329.8 MB; keepProviders
  32.9/32.1 MB -> gone; writeProvidersJSON 15.3/13.6 -> 9.9/14.9 MB.
- poll CPU 4.21/4.27 s -> 4.18/4.10 s; footprint peak 111/116 ->
  112/108 MB.
- /api/state and drift answers byte-identical; /api/providers differs
  only in the providers' "fetched" time.

Not run: the Linux and Windows apps; a save's keepProviders path is
unchanged and was not exercised.
This commit is contained in:
yetone
2026-11-01 09:04:26 +08:00
parent c76bcaea7a
commit fd70def825
4 changed files with 98 additions and 15 deletions
+29 -8
View File
@@ -40,19 +40,40 @@ func lastProvidersPath() string { return filepath.Join(appdir.Cache(), "provider
// keepProviders remembers s as the last-known list, written only when what
// is kept changed.
func keepProviders(s providersJSON) {
sum, err := encodedSum(keptProviders(s)) // as keepState's: no copy to compare
if err != nil {
return
}
keepProvidersSummed(s, sum)
}
// keptProviders is what keepProviders keeps of s.
func keptProviders(s providersJSON) providersFile {
s.Gateway.Calls, s.Gateway.Lanes = nil, nil
s.Moved, s.Added, s.Had, s.Removed, s.Fetching = nil, 0, 0, 0, false
ps := make([]providerJSON, len(s.Providers))
for i, p := range s.Providers {
p.Headers, p.ExtraBody, p.Proxy, p.AccountProxies = nil, nil, "", nil
ps[i] = p
ps[i] = keptProvider(p)
}
s.Providers = ps
f := providersFile{Version: Version, Providers: s}
sum, err := encodedSum(f) // as keepState's: no copy to compare
if err != nil {
return
}
return providersFile{Version: Version, Providers: s}
}
// keptProvider is what is kept of a provider's row.
func keptProvider(p providerJSON) providerJSON {
p.Headers, p.ExtraBody, p.Proxy, p.AccountProxies = nil, nil, "", nil
return p
}
// keepsAllOf reports whether p is kept as it is: keptProvider leaves it
// the same.
func keepsAllOf(p *providerJSON) bool {
return p.Headers == nil && p.ExtraBody == nil && p.Proxy == "" && p.AccountProxies == nil
}
// keepProvidersSummed is keepProviders with the encodedSum of what is kept
// of s already taken (writeProvidersJSON's).
func keepProvidersSummed(s providersJSON, sum [32]byte) {
lastProviders.Lock()
defer lastProviders.Unlock()
if !lastProviders.read {
@@ -63,7 +84,7 @@ func keepProviders(s providersJSON) {
return
}
keptMarshaled.Add(1)
b, err := json.Marshal(f)
b, err := json.Marshal(keptProviders(s))
if err != nil {
return
}
+3 -2
View File
@@ -1202,8 +1202,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
return
}
s := providersState()
writeProvidersJSON(rw, s)
keepProviders(s)
if sum, ok := writeProvidersJSON(rw, s); ok {
keepProvidersSummed(s, sum)
}
})
// Recent-call bodies are read only when their row is opened, not with
// every Providers or Gateway refresh (#1521): forty calls' bodies made
+38 -5
View File
@@ -3,7 +3,9 @@ package gui
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/json"
"io"
"net/http"
)
@@ -15,30 +17,61 @@ const providersNull = `{"providers":null`
// encoded alone. Encoding the answer whole grew a buffer to its size each
// poll: 27 MB of what forty polls of the Providers page allocated with
// real accounts.
func writeProvidersJSON(rw http.ResponseWriter, s providersJSON) {
//
// It returns the encodedSum of what keepProviders keeps of s, taken from
// the same encoding: a row kept as it is is summed as it is written, and
// only one with headers, a proxy or an extra body is encoded again
// without them. Encoding the kept list again only to sum it was 37 MB of
// what forty polls allocated.
func writeProvidersJSON(rw http.ResponseWriter, s providersJSON) ([32]byte, bool) {
rows := s.Providers
s.Providers = nil
f := keptProviders(s)
s.Providers, f.Providers.Providers = nil, nil
tail, err := json.Marshal(s)
if rows == nil || err != nil || !bytes.HasPrefix(tail, []byte(providersNull)) {
keptTail, kerr := json.Marshal(f)
v, _ := json.Marshal(Version)
keptHead := `{"version":` + string(v) + `,"providers":` + providersNull
if rows == nil || err != nil || kerr != nil ||
!bytes.HasPrefix(tail, []byte(providersNull)) || !bytes.HasPrefix(keptTail, []byte(keptHead)) {
s.Providers = rows
writeJSON(rw, s)
return
sum, err := encodedSum(keptProviders(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(`{"providers":[`)
h.Write([]byte(keptHead[:len(keptHead)-len("null")] + "["))
enc := json.NewEncoder(lineless{out})
both := json.NewEncoder(lineless{io.MultiWriter(out, h)})
kept := json.NewEncoder(lineless{h})
for i := range rows {
if i > 0 {
_ = out.WriteByte(',')
h.Write([]byte{','})
}
// a pointer, so a method on *T is used as it is in the slice
if keepsAllOf(&rows[i]) {
if both.Encode(&rows[i]) != nil {
return [32]byte{}, false
}
continue
}
if enc.Encode(&rows[i]) != nil {
return
return [32]byte{}, false
}
k := keptProvider(rows[i])
if kept.Encode(&k) != nil {
return [32]byte{}, false
}
}
_ = out.WriteByte(']')
_, _ = out.Write(tail[len(providersNull):])
_ = out.WriteByte('\n')
h.Write([]byte{']'})
h.Write(keptTail[len(keptHead):])
h.Write([]byte{'\n'})
return [32]byte(h.Sum(nil)), true
}
+28
View File
@@ -6,6 +6,10 @@ import (
"fmt"
"runtime"
"testing"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// bigProviders is an answer the size real accounts give the Providers
@@ -68,3 +72,27 @@ func TestProvidersWriteGrowsNoBufferItsSize(t *testing.T) {
t.Fatalf("writing a %d-byte answer allocated %d bytes, want under half its size", size, per)
}
}
// The sum writeProvidersJSON takes while writing is the one keepProviders
// takes of what it keeps: rows with headers, a proxy or an extra body
// summed without them, the gateway's calls and moved models left out.
func TestProvidersWriteSumsWhatIsKept(t *testing.T) {
secret := bigProviders()
secret.Providers[0].Headers = map[string]string{"X-Key": "k"}
secret.Providers[1].Proxy = "socks5://127.0.0.1:1080"
secret.Providers[2].ExtraBody = provider.ExtraBody{"a": json.RawMessage(`1`)}
secret.Providers[3].AccountProxies = map[string]string{"a": "http://p"}
secret.Gateway.Calls = []gateway.Call{{ID: 1}}
secret.Moved = []agent.Move{{Agent: "codex", Field: "model", From: "a", To: "b"}}
secret.Fetching, secret.Added = true, 2
for _, s := range []providersJSON{bigProviders(), secret, {Providers: []providerJSON{}}, {}} {
sum, ok := writeProvidersJSON(&sinkWriter{}, s)
want, err := encodedSum(keptProviders(s))
if err != nil {
t.Fatal(err)
}
if !ok || sum != want {
t.Fatalf("writing %d providers summed %x (ok %v), want %x", len(s.Providers), sum[:4], ok, want[:4])
}
}
}