Commit Graph
1 Commits
Author SHA1 Message Date
yetone 9329c89c95 settings: an unchanged settings.json is parsed once, and a gateway request reads the shared settings
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)
2026-10-21 07:32:11 +08:00