magpie icon indicating copy to clipboard operation
magpie copied to clipboard

gateway: a vendor that keeps the prompt cached without saying so (OpenAI's prefix cache, Gemini) still moves a conversation on its second turn

Open JasonBuildAI opened this issue 1 month ago • 3 comments

What happens

Affinity: auto (the default) drops the stick as no-cache when the last reply's CacheRead + CacheWrite is under cacheWorth (1024). A vendor that keeps the prompt cached by itself never reports a write, so a first turn reports neither a read nor a write, the conversation is judged no-cache, and the next turn is sent the whole prompt again — to whatever routing puts first, which after a turn is often another key or account. That turn reads nothing, so it is judged no-cache too, and the conversation keeps paying for the whole prompt at every turn.

Two vendors whose cache magpie already parses are affected: OpenAI's automatic prefix cache (prompt_tokens_details.cached_tokens, no write, and the read only from the second turn) and Gemini (cachedContentTokenCount, the same). 7f968b95b fixed exactly this for Anthropic, whose cache_creation_input_tokens counts as written; its body says the rest is not covered:

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.

Minimal reproduction

At fad96ea0 (internal/gateway, Go 1.26.8 windows/amd64): a provider with two keys (k1, k2) and Routing: usage (least used first), whose upstream answers as OpenAI does — prompt_tokens: 3000, prompt_tokens_details.cached_tokens: 0 on the first turn, 2500 on a turn that reads the cache — and one conversation sent twice:

func TestAffinityKeepsACacheTheVendorKeptSilently(t *testing.T) {
	fresh(t)
	v := &silentCache{}                                  // Chat upstream: reports no write, read 0 on the first turn
	serveOn(t, "silent", "k1", []string{"m"}, v, "k2")
	provider.SetRouting("silent", provider.LeastUsed)
	s := New()
	postAs(t, s, "s1", `{"model":"silent/m","messages":[{"role":"user","content":"hi"}]}`)
	postAs(t, s, "s1", `{"model":"silent/m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`)
	a := s.trace.routes[len(s.trace.routes)-1].Affinity
	// second turn
	t.Logf("answered by %s, affinity %+v", v.tried[1], a)
}

Raw output at the fix's base:

second turn went to k2 (no-cache), want k1 kept as cache

The first turn was answered by k1 and built the vendor's cache for that prompt; the second turn went to k2 and was billed the whole prompt again. Routing: usage makes the move certain (least used first), but any order that puts another member first does the same — a group whose order changed, a key back from a rest, a pace/weight order.

Expected

The second turn stays on the account that answered the first and reads the cache that turn built, as it does today when the vendor reports the write (Anthropic) — the rule 7f968b95b put in answered.

Who is harmed

Anyone running Affinity: auto on an OpenAI- or Gemini-served model that routing can answer from more than one key or account: the prompt cache each turn builds is never read, and every turn is charged for the whole prompt (and waits for it). It is the case vilicvane reported on Discord for Anthropic, still open on the two vendors that cache automatically.

Version

fad96ea0 (main, 2026-10-14), Go 1.26.8.

JasonBuildAI avatar Oct 14 '26 16:10 JasonBuildAI

A verified fix for this is ready to take: branch fix/wren-tbd in https://github.com/JasonBuildAI/magpie (public), commit afa81bad, one commit on top of e98440ae.

git fetch https://github.com/JasonBuildAI/magpie.git fix/wren-tbd
git cherry-pick afa81bad

I re-checked this against today's main (3d3a834d, 26 commits on from e98440ae): the cherry-pick applies with no conflict, and the affinity tests below pass there too.

What it does. answered takes the reply's Usage instead of its two cache counts, and where a reply reports neither a read nor a write, the prompt it was sent (Input) stands for the write: the next turn stays as cache rather than moving as no-cache. docs/subsystems/gateway-routing.md and docs/reference.md say so now.

Where it deliberately stops. A reply that reports no usage at all (Input 0) still moves, as does a prompt under cacheWorth (1024). A reply that reports a read or a write is judged on what it reported — that is the cache a move would give up — so a turn whose read fell under cacheWorth still moves, as it did before; substituting a write there would also credit an Anthropic turn that read a cached prefix and created nothing new. The trace's Affinity.CacheWrite carries the prompt the cache now holds, so the Routing page reads "wrote 3000" where a silent-cache vendor reported no write; the page itself is unchanged.

Evidence (raw output in the commit body): the new TestAffinityKeepsACacheTheVendorKeptSilently fails at the base and passes with the change; TestAffinityKeepsACacheJustWritten passes as it did; gofmt -l on the changed files, go vet ./... (all three targets) and go build (all three) are clean; go test -tags nogui -count=1 -timeout 45m ./... passes except for reds that fail the same in a fresh worktree at e98440ae without the change (agent 4, gui 4, library 3, gateway 2 and one each in backup, davsync, pluginrt, provider, sessions, update, usage).

I could not open the pull request myself: yetone/magpie's pull_request_creation_policy is collaborators_only, so gh pr create answers "JasonBuildAI does not have the correct permissions to execute CreatePullRequest" while the same call on my fork succeeds. Hence the branch above rather than a PR.

AI disclosure: this change was drafted with AI assistance at my request, under my direction and review.

JasonBuildAI avatar Oct 14 '26 17:10 JasonBuildAI

Thanks @JasonBuildAI. Your change is in as 7c5bfd7a1, with your authorship kept.

Cause. OpenAI's automatic prefix cache and Gemini's implicit cache report a first turn with neither a cache read nor a write. Auto affinity read that as no cache and moved the second turn as "no-cache" to another key, which had to be sent the whole prompt again.

Fix. When a reply reports neither, the prompt it was sent now counts as written, so the conversation stays. A reply with no usage at all, or a prompt under 1024 tokens, still moves as before.

Extra tests (932a62d5e) cover three more cases:

  • Gemini's usageMetadata shape;
  • the stick read back from affinity.json after a restart;
  • a 600-token prompt, which still moves.

With the change taken out, both your test and mine fail with "no-cache, want cache".

What was run:

  • go test -tags nogui ./... on macOS: every package ok.
  • go vet on darwin, linux and windows: clean.

This ships in the next release after v0.1.1231. I'll leave this open until you confirm the second turn stays on its key.

yetone avatar Oct 14 '26 19:10 yetone

Confirmed on main (82f48f09), Windows box, Go 1.26.8 - the silence cases pass, including the ones your follow-up added:

> go test -tags nogui -count=1 -run TestAffinity -v ./internal/gateway/
--- PASS: TestAffinityKeepsACacheJustWritten (1.80s)
--- PASS: TestAffinityKeepsACacheTheVendorKeptSilently (0.77s)
--- PASS: TestAffinitySilentCacheGeminiRestartAndSmall (1.67s)
--- PASS: TestAffinity (5.01s)
ok  github.com/yetone/magpie/internal/gateway  9.813s

So the second turn of a silently cached conversation stays on the key that answered the first (OpenAI's prefix cache and Gemini's shape), it is still kept after a restart, a prompt under 1024 tokens and a reply with no usage at all still move, and the written-cache case is unchanged. That is the behaviour the report asked for.

My branch fix/wren-tbd (afa81bad) is what landed as 7c5bfd7a1 and 932a62d5e, so it stays unmerged. Both commits are on main but not in v0.1.1242, so this ships in the next release. Closing.

AI disclosure: this verification was produced with AI assistance at my request, under my direction and review.

JasonBuildAI avatar Oct 14 '26 21:10 JasonBuildAI