gui: the kept state and providers are marshaled only when they changed

keepState and keepProviders ran json.Marshal on every /api/state and
/api/providers poll to compare the answer with the one kept on disk.
They now keep a sha256 of what was written and hash the new answer
into it with an Encoder; only a changed answer is marshaled and
written. json.Marshal there was 38.6 MB (keepState 25.9 MB,
keepProviders 12.7 MB) of what twenty window polls allocated with
real accounts (m2463 profile).

Test: TestKeptStateMarshaledOnlyWhenChanged. Twenty identical keeps
marshal nothing, nor does a keep after the file is read again; a
changed state is marshaled once and read back.

Run on mote, at this tree on dd7442f28:
- gofmt, go vet (darwin, windows, linux): ok
- the new test alone 3 times: ok
- broken by hand (the sum check made never true): red, "20 polls of
  the same state and list marshaled them 20 times, want 0"
- go test ./internal/gui: every test ok except the known
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestMainWindowCorners (#3949)

Not run: an A/B with the real-account sandbox for this change alone;
it goes with the next batch's profile.
This commit is contained in:
yetone
2026-11-01 04:46:38 +08:00
parent 606743831e
commit 6a23d9d755
3 changed files with 101 additions and 14 deletions
+50
View File
@@ -0,0 +1,50 @@
package gui
import (
"testing"
)
// Each poll of the Agents and Providers pages marshaled the state it keeps
// only to find it the same as kept: 38 MB of what twenty polls allocated.
// The same state is now compared by its hash, and marshaled only when it
// changed, by this run or against the file the run before kept.
func TestKeptStateMarshaledOnlyWhenChanged(t *testing.T) {
sandboxHome(t)
forgetLastState()
forgetLastProviders()
t.Cleanup(forgetLastState)
t.Cleanup(forgetLastProviders)
s := stateJSON{Agents: []agentJSON{{ID: "codex", Name: "Codex"}}}
ps := providersJSON{Providers: []providerJSON{{ID: "relay", Name: "Relay"}}}
keepState(s)
keepProviders(ps)
before := keptMarshaled.Load()
for range 20 {
keepState(s)
keepProviders(ps)
}
if n := keptMarshaled.Load() - before; n != 0 {
t.Fatalf("20 polls of the same state and list marshaled them %d times, want 0", n)
}
// a new run reads the file the last one kept, and finds it the same
forgetLastState()
forgetLastProviders()
keepState(s)
keepProviders(ps)
if n := keptMarshaled.Load() - before; n != 0 {
t.Fatalf("the state as the last run kept it was marshaled %d times, want 0", n)
}
s.Agents = append(s.Agents, agentJSON{ID: "claude", Name: "Claude Code"})
keepState(s)
if n := keptMarshaled.Load() - before; n != 1 {
t.Fatalf("a state changed was marshaled %d times, want 1", n)
}
got, ok := lastKnown()
if !ok || len(got.Agents) != 2 || got.Agents[1].ID != "claude" {
t.Fatalf("the changed state isn't the one kept: %+v", got.Agents)
}
forgetLastState()
if got, ok := lastKnown(); !ok || len(got.Agents) != 2 {
t.Fatalf("the changed state isn't in the file: %+v", got.Agents)
}
}
+12 -6
View File
@@ -1,7 +1,6 @@
package gui
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
@@ -28,6 +27,7 @@ var lastProviders struct {
sync.Mutex
kept []byte
read bool
sum [32]byte // kept's keptSum
}
type providersFile struct {
@@ -48,7 +48,8 @@ func keepProviders(s providersJSON) {
ps[i] = p
}
s.Providers = ps
b, err := json.Marshal(providersFile{Version: Version, Providers: s})
f := providersFile{Version: Version, Providers: s}
sum, err := encodedSum(f) // as keepState's: no copy to compare
if err != nil {
return
}
@@ -56,12 +57,17 @@ func keepProviders(s providersJSON) {
defer lastProviders.Unlock()
if !lastProviders.read {
lastProviders.kept, _ = os.ReadFile(lastProvidersPath())
lastProviders.read = true
lastProviders.read, lastProviders.sum = true, keptSum(lastProviders.kept)
}
if bytes.Equal(b, lastProviders.kept) {
if sum == lastProviders.sum {
return
}
lastProviders.kept = b
keptMarshaled.Add(1)
b, err := json.Marshal(f)
if err != nil {
return
}
lastProviders.kept, lastProviders.sum = b, sum
// only this user's to read: it names their accounts
if _, err := os.Stat(lastProvidersPath()); os.IsNotExist(err) {
os.MkdirAll(filepath.Dir(lastProvidersPath()), 0o700)
@@ -76,7 +82,7 @@ func lastKnownProviders() (json.RawMessage, bool) {
lastProviders.Lock()
if !lastProviders.read {
lastProviders.kept, _ = os.ReadFile(lastProvidersPath())
lastProviders.read = true
lastProviders.read, lastProviders.sum = true, keptSum(lastProviders.kept)
}
b := lastProviders.kept
lastProviders.Unlock()
+39 -8
View File
@@ -1,11 +1,12 @@
package gui
import (
"bytes"
"crypto/sha256"
"encoding/json"
"os"
"path/filepath"
"sync"
"sync/atomic"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/settings"
@@ -27,8 +28,32 @@ import (
var lastState struct {
sync.Mutex
kept []byte // the last state built, as stateFile holds it
read bool // the file was looked at (or kept was set)
kept []byte // the last state built, as stateFile holds it
read bool // the file was looked at (or kept was set)
sum [32]byte // kept's keptSum
}
// keptMarshaled counts the states and lists kept marshaled, for a test.
var keptMarshaled atomic.Int64
// encodedSum is the hash of v as json.Marshal writes it, with a newline
// after it, found without a copy of those bytes: each poll of the Agents
// and Providers pages marshaled what it keeps, the same as it was nearly
// always, only to compare it, 38 MB of what twenty polls allocated.
func encodedSum(v any) ([32]byte, error) {
h := sha256.New()
if err := json.NewEncoder(h).Encode(v); err != nil {
return [32]byte{}, err
}
return [32]byte(h.Sum(nil)), nil
}
// keptSum is encodedSum of what kept is the marshaled bytes of.
func keptSum(kept []byte) [32]byte {
h := sha256.New()
h.Write(kept)
h.Write([]byte{'\n'})
return [32]byte(h.Sum(nil))
}
// stateFile is the last-known state, with the version that wrote it: an
@@ -49,7 +74,8 @@ 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
b, err := json.Marshal(stateFile{Version: Version, State: s})
f := stateFile{Version: Version, State: s}
sum, err := encodedSum(f)
if err != nil {
return
}
@@ -57,12 +83,17 @@ func keepState(s stateJSON) {
defer lastState.Unlock()
if !lastState.read {
lastState.kept, _ = os.ReadFile(lastStatePath())
lastState.read = true
lastState.read, lastState.sum = true, keptSum(lastState.kept)
}
if bytes.Equal(b, lastState.kept) {
if sum == lastState.sum {
return
}
lastState.kept = b
keptMarshaled.Add(1)
b, err := json.Marshal(f)
if err != nil {
return
}
lastState.kept, lastState.sum = b, sum
p := lastStatePath()
if os.MkdirAll(filepath.Dir(p), 0o755) == nil {
_ = steady.WriteFile(p, b, 0o644)
@@ -76,7 +107,7 @@ func lastKnown() (stateJSON, bool) {
lastState.Lock()
if !lastState.read {
lastState.kept, _ = os.ReadFile(lastStatePath())
lastState.read = true
lastState.read, lastState.sum = true, keptSum(lastState.kept)
}
b := lastState.kept
lastState.Unlock()