settings.parse ran json.Unmarshal on every Load, and one gateway request
called Load six or seven times (Provider.Efforts, ImageOverride,
masking.options, withWires, redactionWanted, recordConversation,
namesMember). parse now keeps the last parsed value keyed by the file's
bytes, and hands Load a deep clone (internal/settings/clone.go), so every
caller still owns what it gets. settings.Shared() returns one read-only
value for the request path, its slices held at len==cap so an append
reallocates instead of reaching the shared array; the seven callers above
moved to it after checking none writes what it reads. A file that doesn't
parse is not memoized: it falls back as before (lastgood), and Shared
then returns that result, never the last good parse, so a failed read
can't keep a looser list. LoadChecked callers (allow list, image fetch
guard, disabled) stay on Load.
Measured with a 200-request probe through the gateway (5 providers, a
~9.9KB settings.json), before (origin/main 2201b6628) -> after:
chat 7.1 parses/request, 570-571 KB/request -> 0.0, 216-242 KB
messages 6.1-6.2 parses, 537-556 KB -> 0.0, 255-261 KB
responses 6.2-6.3 parses, 569-574 KB -> 0.0, 268-277 KB
Tests: TestRequestsParseUnchangedSettingsOnce (gateway, 30 requests must
parse fewer than 30 times), TestUnchangedSettingsParsedOnce,
TestLoadIsTheCallersOwn, TestSharedAppendReallocates,
TestUnreadableSettingsNotTheLastParsed, TestCloneSharesNothing. Broken by
hand, each went red:
- old code: "settings.json parsed 226 times for 30 requests with the
file unchanged"
- memo hit off: "an unchanged settings.json was parsed 200 more times
in 300 reads"
- shallow clone: TestLoadIsTheCallersOwn, TestSharedAppendReallocates,
TestCloneSharesNothing ("Settings.RedactKinds is shared", ...)
- Shared keeping the last parse on a bad file: "Shared kept the last
file's list: [10.0.0.1]"
- no len==cap clone: "appends reached the shared list"
Run at this commit's tree (go1.26.8 darwin/arm64, sandbox HOME):
gofmt -l .: nothing
GOOS=linux go vet -tags nogui ./...: ok
GOOS=windows go vet -tags nogui ./...: ok
go test -tags nogui -race -timeout 45m ./internal/settings
./internal/masking ./internal/provider ./internal/gateway: ok
(settings 388s, provider 836s, gateway 2081s)
set -o pipefail; go test -tags nogui -timeout 45m ./...: ok, every
package (66 ok, 20 with no test files)
82 lines
2.9 KiB
Go
82 lines
2.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// A heap profile of a gateway at work (~1,000 requests in 10 minutes)
|
|
// had settings.json parsed many times for each request, ~800 MB in all:
|
|
// redaction, the model wires, efforts, images, conversations and member
|
|
// names each read the settings again. An unchanged file is parsed once
|
|
// however many requests are served, and what the requests share of it is
|
|
// left as the file says.
|
|
//
|
|
// Counted, not timed: before, each request parsed it seven times.
|
|
func TestRequestsParseUnchangedSettingsOnce(t *testing.T) {
|
|
fresh(t)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.ReadAll(r.Body)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"pong"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1,"total_tokens":4}}`)
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// a long-used magpie's settings: answers about many models
|
|
images := map[string]bool{}
|
|
for i := range 200 {
|
|
images[fmt.Sprintf("p%d/model-%d", i%30, i)] = i%2 == 0
|
|
}
|
|
raw, err := json.Marshal(map[string]any{"modelImages": images, "redactWords": []string{"hunter2"}, "modelWires": map[string]string{"relay/m1": "m1"}})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
was, _ := os.ReadFile(settings.Path())
|
|
t.Cleanup(func() { os.WriteFile(settings.Path(), was, 0o600) })
|
|
os.MkdirAll(filepath.Dir(settings.Path()), 0o755)
|
|
if err := os.WriteFile(settings.Path(), raw, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gw := httptest.NewServer(New().Handler())
|
|
t.Cleanup(gw.Close)
|
|
ask := func() {
|
|
t.Helper()
|
|
res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"relay/m1","messages":[{"role":"user","content":"my password is hunter2"}]}`))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b, _ := io.ReadAll(res.Body)
|
|
res.Body.Close()
|
|
if res.StatusCode != 200 {
|
|
t.Fatalf("status %d: %s", res.StatusCode, b)
|
|
}
|
|
}
|
|
ask()
|
|
const requests = 30
|
|
before := settings.Parses()
|
|
for range requests {
|
|
ask()
|
|
}
|
|
if n := settings.Parses() - before; n >= requests {
|
|
t.Fatalf("settings.json parsed %d times for %d requests with the file unchanged", n, requests)
|
|
}
|
|
var want settings.Settings
|
|
json.Unmarshal(raw, &want)
|
|
if got := settings.Shared(); !reflect.DeepEqual(got.ModelImages, want.ModelImages) || !reflect.DeepEqual(got.RedactWords, want.RedactWords) || !reflect.DeepEqual(got.ModelWires, want.ModelWires) {
|
|
t.Fatalf("the requests changed the shared settings: %v %v", got.RedactWords, got.ModelWires)
|
|
}
|
|
}
|