Files
magpie/internal/gateway/affinity_cache_write_test.go
T
yetone 7f968b95dd gateway: auto affinity keeps a conversation on the cache its last reply wrote, not only one it read (vilicvane on Discord)
Affinity's auto mode kept a conversation on its last answerer across turns
only while that reply had read at least cacheWorth (1024) tokens from the
vendor's cache. A first turn reads nothing and writes the whole prompt
(Anthropic's cache_creation_input_tokens), so the second turn was moved as
"no-cache" and the cache just built was thrown away (vilicvane on Discord,
「会话保持 → 自动」: 「新的 cache 都建好了,再切走不可惜吗?」).

answered() is now given the usage's CacheWrite beside CacheRead (both
already parsed at that call site for every route: Anthropic, Chat's
cache_write_tokens / cache_creation_input_tokens, Cursor, Command Code,
plugins), and affine counts read + written against cacheWorth. The stick
keeps cacheWrite in memory and in affinity.json (`cacheWrite`, omitempty);
a file from before has no such field and reads as 0, so an old stick is
judged by its read alone, as before. The trace's Affinity carries
CacheWrite, and the Routing page's "cache" and "no-cache" explanations say
what was read and what was written (en, zh, zh-TW, ja, de).

Not covered: a vendor that caches without reporting a write (OpenAI's
automatic prefix cache, Gemini) still reports CacheWrite 0 on a first turn,
so its second turn may still move. Noted in gateway-routing.md.

Docs: docs/subsystems/gateway-routing.md (affinity bullet), docs/reference.md
(step 6 of how magpie picks an account).

Run:
- TestAffinityKeepsACacheJustWritten (new): an Anthropic Messages upstream
  streaming cache_creation_input_tokens 3000 / read 0; the second turn is
  kept as "cache", also across a restart (affinity.json reloaded); 600+600
  is kept, 300+300 moves as "no-cache". Broken by hand twice and watched
  red: the old `st.cacheRead < cacheWorth` (written: why no-cache), and
  stickOf not reading CacheWrite from the file (restarted: no-cache).
- routing-affinity-cache-write.test.cjs (new): chromium and webkit, 1100
  and 420 wide, en/zh/zh-TW/ja/de, 20/20 pass; red on the old routing.js
  and i18n.js. i18n-keys.test.cjs and routing-account-identity.test.cjs
  pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  internal/gateway.
- go test ./internal/gateway/...: all pass except
  TestAgentGoneInTheRetryPause/group_replan, which failed in two full runs
  at load average 150-380 and passes alone (-count=3); its fixed 100ms
  sleep before cancelling assumes the pause has begun. Filed as #2175; it
  never reaches the affinity path this changes (a first request).
- go test -timeout 40m ./... at load ~300-377: 50 packages ok; agent and
  gateway hit the 40m package timeout (no test failed before it); gui's
  TestSetAnswersWhileDevinAndProvidersHang (#1375) and
  TestMainWindowCorners (#1936) failed, both filed load reds.
  internal/agent rerun alone: ok (1008s at load ~200).
- Not tried against a real Anthropic account.
2026-10-14 21:05:26 +08:00

106 lines
3.7 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// cacheWriter is an Anthropic Messages upstream that answers as each key,
// reporting the cache as Anthropic does: a first turn writes the prompt
// (cache_creation_input_tokens) and reads none of it.
type cacheWriter struct {
mu sync.Mutex
tried []string
read, wrote int
}
func (c *cacheWriter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
key := r.Header.Get("x-api-key")
if key == "" {
key = strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
}
c.mu.Lock()
c.tried = append(c.tried, key)
read, wrote := c.read, c.wrote
c.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
usage := `"cache_read_input_tokens":` + itoa(read) + `,"cache_creation_input_tokens":` + itoa(wrote)
for _, ev := range []string{
`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[],"usage":{"input_tokens":12,"output_tokens":1,` + usage + `}}}`,
`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from ` + key + `"}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`,
`{"type":"message_stop"}`,
} {
var t struct {
Type string `json:"type"`
}
json.Unmarshal([]byte(ev), &t)
io.WriteString(w, "event: "+t.Type+"\ndata: "+ev+"\n\n")
}
}
// What the last reply wrote to the vendor's cache counts with what it
// read: the first turn of a conversation reads nothing and writes the
// whole prompt, and its second turn stays to read it (vilicvane on
// Discord: 「会话保持 → 自动」 moved the second turn as "no-cache", and the
// cache just built was thrown away). Kept across a restart too, as the
// file has it; a reply that neither read nor wrote enough still moves.
func TestAffinityKeepsACacheJustWritten(t *testing.T) {
const (
first = `{"model":"cw/m","messages":[{"role":"user","content":"hi"}]}`
again = `{"model":"cw/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`
)
for _, c := range []struct {
name string
read, wrote int
restart bool
why string
}{
{"written", 0, 3000, false, "cache"},
{"written, restarted", 0, 3000, true, "cache"},
{"read and written together", 600, 600, false, "cache"},
{"too little either way", 300, 300, false, "no-cache"},
} {
fresh(t)
v := &cacheWriter{read: c.read, wrote: c.wrote}
up := httptest.NewServer(v)
t.Cleanup(up.Close)
p := provider.Provider{ID: "cw", Name: "CW", Key: "k1", Models: []string{"m"}, Anthropic: up.URL + "/v1",
Keys: []provider.KeyAccount{{Key: "k2"}}}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
s := New()
if code, body := postAs(t, s, "s1", first); code != 200 {
t.Fatalf("%s: first turn %d %s", c.name, code, body)
}
if c.restart {
sticks.Lock()
sticks.m, sticks.from, sticks.mod = map[string]stick{}, "", time.Time{}
sticks.Unlock()
s = New()
}
if code, body := postAs(t, s, "s1", again); code != 200 {
t.Fatalf("%s: second turn %d %s", c.name, code, body)
}
a := s.trace.routes[len(s.trace.routes)-1].Affinity
if a == nil || a.Why != c.why || a.Kept != (c.why == "cache") {
t.Fatalf("%s: affinity %+v, want %s", c.name, a, c.why)
}
if a.CacheRead != c.read || a.CacheWrite != c.wrote {
t.Fatalf("%s: trace tells read %d wrote %d, want %d and %d", c.name, a.CacheRead, a.CacheWrite, c.read, c.wrote)
}
}
}