Files
magpie/internal/agent/via_shared_test.go
T
yetone dd7442f283 agent: a look at the via-magpie options shares the kept list
viaMagpie handed every caller its own copy of the options list it keeps
per stamp, and a window poll asks for it from most agents' fields and
pickers. In a real-account sandbox (abr.sh, 20 polls of drift, state and
providers on v0.1.2463) those copies were 33.7 MB of slices.Clone, plus
~8 MB more on the way, of the 713 MB the polls allocated.

viaMagpieShared returns the kept list itself, clipped, so an append
makes the caller's own array. The 58 callers that only read it, or
append onto it, now take it; viaMagpie (a copy) stays for the ones that
change it.

TestKeptListSharedWithoutACopy checks that 20 shared looks return the
kept array, and that an append onto a shared look and a write into
get's copy leave the kept list as it was.

Run on mote at this tree:
- gofmt, go vet (darwin, GOOS=windows, GOOS=linux with gateway),
  go build ./...: ok.
- Broken by hand (shared returns slices.Clone): the test is red, "a
  shared look copies the kept list".
- go test -count=1 ./internal/agent: ok (480s).

Not run: internal/gateway and internal/gui packages on this tree.
2026-11-01 04:25:59 +08:00

44 lines
1.3 KiB
Go

package agent
import (
"reflect"
"slices"
"strconv"
"testing"
)
// A look that only reads a kept list, or appends it onto one of its own,
// shares the list: a copy for each look was 42 MB of what twenty window
// polls allocated. get still hands each caller a copy of its own, and an
// append onto the shared list never writes into what is kept.
func TestKeptListSharedWithoutACopy(t *testing.T) {
var s stampedLists[Option]
build := func() []Option {
out := make([]Option, 500)
for i := range out {
out[i] = Option{Value: "p/m" + strconv.Itoa(i), Note: "via magpie"}
}
return out
}
want := slices.Clone(s.shared("k", build))
for range 20 {
// the kept array itself, not a copy of it (~100 KB for 500); a
// change of the stamp while the package's tests run builds it
// again, and that one is kept
got := s.shared("k", build)
s.Lock()
kept := s.m["k"].list
s.Unlock()
if &got[0] != &kept[0] {
t.Fatal("a shared look copies the kept list")
}
}
grown := append(s.shared("k", build), Option{Value: "mine"})
grown[0].Value = "changed"
own := s.get("k", build)
own[1].Value = "changed too"
if got := s.shared("k", build); !reflect.DeepEqual(got, want) {
t.Fatalf("the kept list was written into: %q, %q", got[0].Value, got[1].Value)
}
}