Files
magpie/internal/gateway/masked_sent_test.go
T
yetone 49f15d1244 masking: a record names the provider the request went to, not the group's first member (Max You and Linka on Discord)
Linka on Discord: Insights › Masking's records said WorkBuddy AI, the
first member of their auto group, for requests that Codex in the same
group had answered. Max You: providers no route sends to show up under
Privacy all the same.

Cause: serve() recorded the masking (noteMasked) as the route began,
with p.ID, the first planned provider, before any try. A request the
first member failed, or a member resting or unable to serve, went on
to the next, and the record (on disk, and counted into the flow and
the provider filter) kept the first. Embeddings recorded tries[0] and
video the same way.

Fix: maskrec.Hold keeps a record in memory at once (the route's badge
and the answer's Restored need its key) and writes it to disk only
when done is told the provider and model of the last try.
noteMaskedUntil wraps it, and serve, embeddings and video call done
in a defer with call.Provider and the model tried last. A request
that never reached a try keeps the planned one, as before. Since a
long request's line is now written after later ones, List sorts each
day's lines by key, so paging with before skips nothing.

Old records keep the name they were written with; there is no record
of which member had them. They leave with the 30 days.

Tests:
- TestMaskedRecordNamesTheProviderThatHadIt (gateway): a group a/m,
  b/m, a answers 500, b 200, with Mask secrets on; chat and
  embeddings. On the old code both subtests fail:
    masked_sent_test.go:96: recorded on "a", the request went to b
- TestHoldNamesWhoHadIt (maskrec): the held record goes on disk with
  done's provider and model, done's second call counts for nothing,
  Sum counts that provider, and List pages a late-written record in
  key order. With the sort taken out it fails on the first page.

Run at this tree (base a1e91e500), sandbox HOME, caches pinned:
- gofmt -l clean; go vet darwin, linux (nogui), windows on gateway
  and maskrec; builds darwin, linux nogui, windows.
- go test -tags nogui -count=1 -timeout 45m ./internal/maskrec/
  ./internal/gui/ ./internal/gateway/: ok, ok (75s), ok (523s).
- The full ./... suite was not run: other sessions held the machine's
  suite slot.

- Rebased onto ef0a03e13 (no change under internal/gateway or
  internal/maskrec since a1e91e500); builds on 3 OSes and the Mask/Hold
  tests of both packages ok again at the pushed head.

No GUI file changed. Not tried: a real group failover in the app.
2026-10-26 15:29:36 +08:00

104 lines
4.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"github.com/yetone/magpie/internal/maskrec"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// A masked request's record has, in memory, the body as its vendor got
// it, how long masking took, and, once the answer is done, how many
// places of the answer had each value put back: the 脱敏 page reads them.
func TestMaskedRecordKeepsSentAndBack(t *testing.T) {
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
ph := regexp.MustCompile(`\{\{API_KEY_[0-9a-z]{8}\}\}`)
var got []byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, _ = io.ReadAll(r.Body)
p := ph.FindString(string(got))
b, _ := json.Marshal(p + " and " + p)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":`+string(b)+`},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
}))
defer up.Close()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
t.Fatal(err)
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","messages":[{"role":"user","content":"key `+key+`"}]}`)))
p := ph.FindString(string(got))
if rec.Code != 200 || p == "" || strings.Count(rec.Body.String(), key) != 2 {
t.Fatalf("%d, sent %s, answered %s", rec.Code, got, rec.Body)
}
rs, _ := maskrec.List(0, 1, maskrec.Filter{})
if len(rs) != 1 {
t.Fatal("nothing recorded")
}
r, ok := maskrec.Get(rs[0].Key)
if !ok || r.Back[p] != 2 || r.Took <= 0 {
t.Fatalf("record: %+v", r)
}
sent, ok := maskrec.SentOf(r.Key)
if !ok || !strings.Contains(sent, p) || strings.Contains(sent, key) {
t.Fatalf("sent %q %v", sent, ok)
}
}
// A masked request a group's first member fails is recorded on the member
// that had it last, not on the first: Max You and Linka on Discord found
// Privacy's records, and the flow on Insights › Masking, naming the
// group's first provider, which no request had reached. A chat and an
// embedding both.
func TestMaskedRecordNamesTheProviderThatHadIt(t *testing.T) {
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
const embedded = `{"object":"list","data":[{"object":"embedding","index":0,"embedding":[0.1,0.2]}],"model":"m","usage":{"prompt_tokens":3,"total_tokens":3}}`
for _, x := range []struct{ path, body, ok string }{
{"/v1/chat/completions", `{"model":"group/g","messages":[{"role":"user","content":"key ` + key + `"}]}`, chatOK},
{"/v1/embeddings", `{"model":"group/g","input":"key ` + key + `"}`, embedded},
} {
t.Run(x.path, func(t *testing.T) {
fresh(t)
a := &scripted{replies: []reply{{500, "", `{"error":{"message":"down"}}`}}}
b := &scripted{replies: []reply{{200, "", x.ok}}}
scriptedOn(t, "a", provider.Chat, a)
scriptedOn(t, "b", provider.Chat, b)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
t.Fatal(err)
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", x.path, strings.NewReader(x.body)))
if rec.Code != 200 || a.n != 1 || b.n != 1 {
t.Fatalf("%d %s (a %d, b %d)", rec.Code, rec.Body, a.n, b.n)
}
rs, _ := maskrec.List(0, 1, maskrec.Filter{})
if len(rs) != 1 || rs[0].N == 0 {
t.Fatalf("records %+v", rs)
}
if got := rs[0].Provider; got != "b" {
t.Fatalf("recorded on %q, the request went to b", got)
}
if r, _ := maskrec.Get(rs[0].Key); r.Provider != "b" || r.Model != "m" {
t.Fatalf("record %s/%s", r.Provider, r.Model)
}
})
}
}