Files
magpie/internal/gateway/usage_cache_zero_split_test.go
yetone 665b9aff12 gateway: a reply of several requests tells the last one's prompt, bills them all
Claude Code reads a reply's input, cache_creation and cache_read as how
full its conversation is. A reply more than one upstream request made
summed all three across them. In the bridge: Claude Code's own
ToolSearch/WebSearch going on into the answering message, a TUI message
written after its call was told (lateUsage), a cut stream's retry
(b42ff722). Each later request re-sends what the earlier one had, so the
reporter's TaskStop reply after a ToolSearch said cache_read 1,154,857
(577,009 + 577,848) and cache_creation 829 (253 + 576) for a ~577k
conversation, and Claude Code compacted early. 12 of their 30 replies
after ToolSearch were about 2x.

The translated route summed the same way across its tries (#5115): the
empty reply asked again (#667), a loop's re-ask (#1359), a cut reply's
continuation (#853), and search.go's web search rounds. The Anthropic
passthrough has no in-reply fold; each try is its own call.

Usage.after (claude_subscription.go) replaces plus at these joins: the
client is told the last request's input, cache writes and cache reads,
and every request's output and reasoning (all of it was streamed). The
earlier requests' prompts go in Deferred, which the ledger bills
(billed()) and no encoder tells. Usage.restart makes a later request's
prompt counts replace the earlier's, a zero too, so a later request that
reads nothing from the cache isn't told, or billed again, the earlier's
reads. Cache writes are last-only for the client as well: the later
request reads what the earlier wrote, so summed they count it twice.
ggbdpq's #5115 analysis named the translated route's case; no code of
theirs was used.

Tests (usage_last_prompt_test.go), on the reporter's numbers:
- TestClaudeOwnCallReplyTellsLastPrompt: bridge, told 6/576/577848,
  billed 8/829/1154857; and a second request that missed the cache.
- TestClaudeTUILateMessagePromptNotTold: interactive mode's late message.
- TestRetriedReplyTellsLastPrompt: Gemini three reasoning-only replies
  then an answer, Chat and Anthropic clients; ledger has all four.
- TestLaterTryZeroCacheReadNotTold: a continuation and a search round
  whose later request reads 0 from the cache.
Tests that pinned the summed client numbers now pin the last request's
and check the billed sum (CachePartialUpdateMatrix, Probe1717 zero split,
cut stream retry, own WebSearch, search rounds, StreamCutUsage renamed
TestStreamCutUsageTellsLastTry).

Run (mote, Go 1.26.8, -tags nogui):
- The new tests on origin/main ca77a9ea8: red, the client told
  8/829/1154857 (the report's numbers), prompt_tokens 2,000,000 for
  four 500k tries.
- Broken by hand: restart dropped -> TestClaudeCutStreamGoesOnInRetry
  and the cache-missed case red (reads billed twice); after() put back
  to plus -> 12 tests red; restart on the translated tries dropped ->
  TestLaterTryZeroCacheReadNotTold red (cache reads 200 billed, 111
  told). The last one was green before that test was added.
- go test ./internal/gateway/ whole: ok except
  TestClaudeInternalMessagesKeepCacheWrites, which pinned the sum and
  was updated after; that test with the usage, cache, search,
  continuation and TUI tests then ok (61.8s).
- go vet ./internal/gateway for darwin, linux and windows; gofmt clean.
- The full suite runs after the push (mote's suite lock held 3h+ by
  another session).

Not tried: a real Claude Code account or the real TUI, the reporter's
session, a real Gemini/translated provider, Windows or Linux runs of
the package.

Reported-by: sleepy_shibe (Discord)
2026-11-07 10:03:52 +08:00

163 lines
6.8 KiB
Go

package gateway
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
const (
zeroSplitBefore = `"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":10}`
zeroSplitStart = `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`
// zeroSplitBefore1h is the first request's 1h writes in zeroSplitBefore
zeroSplitBefore1h = 10
zeroSplitDelta = `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7,"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}}`
)
func cacheSplitRoundStart(fields string) string {
return `{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"m","content":[],"usage":{` + fields + `}}}`
}
func wantCacheLedger(t *testing.T, hour int) {
t.Helper()
records := usage.Load(time.Time{})
if len(records) != 1 {
t.Fatalf("ledger records = %d, want 1", len(records))
}
if u := records[0]; u.CacheWrite != 50 || u.CacheWrite1h != hour {
t.Errorf("ledger writes: %d/hour%d, want 50/hour%d", u.CacheWrite, u.CacheWrite1h, hour)
}
}
func TestProbe1717ContinuationTotalZeroSplit(t *testing.T) {
checkCacheContinuation(t, zeroSplitDelta, 15)
}
func checkCacheContinuation(t *testing.T, delta string, hour int) {
t.Helper()
f := &cutAnthropic{
cuts: map[int][]string{0: {cacheSplitRoundStart(zeroSplitBefore), anthText("hel")}},
whole: []string{cacheSplitRoundStart(zeroSplitStart), anthText("lo"), delta, `{"type":"message_stop"}`},
}
body := continuationChatServer(t, "m", f)
if f.calls() != 2 || chatTextOf(body) != "hello" {
t.Fatalf("continuation failed: calls%d body%s", f.calls(), body)
}
if prefill, ok := f.lastAssistantText(t, 1); !ok || prefill != "hel" {
t.Fatalf("retry did not continue cut reply: %q %t", prefill, ok)
}
u := chatUsageOf(body)
details, _ := u["prompt_tokens_details"].(map[string]any)
// the client is told the last try's writes, the ledger every try's
if details["cache_write_tokens"] != 20.0 {
t.Errorf("client cache writes=%v, want the last try's 20", details["cache_write_tokens"])
}
wantCacheLedger(t, hour)
}
func TestProbe1717SearchTotalZeroSplit(t *testing.T) {
checkCacheSearch(t, zeroSplitDelta, 15)
}
func checkCacheSearch(t *testing.T, delta string, hour int) {
t.Helper()
for _, stream := range []bool{true, false} {
t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) {
fresh(t)
apis := newSearchAPIs(t)
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
asked = append(asked, string(b))
n := len(asked)
mu.Unlock()
if n == 1 {
writeStream(w, []string{
cacheSplitRoundStart(zeroSplitBefore),
`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_1","name":"web_search","input":{}}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"latest go\"}"}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}`,
`{"type":"message_stop"}`,
}, false, "")
return
}
writeStream(w, []string{cacheSplitRoundStart(zeroSplitStart), anthText("answer"), delta, `{"type":"message_stop"}`}, false, "")
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
body := fmt.Sprintf(`{"model":"up/m","max_tokens":100,"stream":%t,"messages":[{"role":"user","content":"latest go"}],"tools":[{"type":"web_search_20250305","name":"web_search"}]}`, stream)
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
r.Header.Set("x-api-key", Token)
r.RemoteAddr = "127.0.0.1:12345"
w := httptest.NewRecorder()
lanGuard(New().Handler()).ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("search reply=%d %s", w.Code, w.Body)
}
mu.Lock()
secondRound := len(asked) == 2 && strings.Contains(asked[1], `"tool_result"`) && strings.Contains(asked[1], "https://go.dev/dl/")
mu.Unlock()
if !secondRound {
t.Fatal("model did not receive search results in a second round")
}
client := newSniffer(provider.Anthropic, w.Header().Get("Content-Type"))
client.write(w.Body.Bytes())
u := client.usage()
if u.CacheWrite != 20 || u.CacheWrite1h != hour-zeroSplitBefore1h {
t.Errorf("client writes: %d/hour%d, want the last round's 20/hour%d", u.CacheWrite, u.CacheWrite1h, hour-zeroSplitBefore1h)
}
wantCacheLedger(t, hour)
})
}
}
func TestProbe1717BridgeTotalZeroSplit(t *testing.T) {
ev := func(e string) string { return `{"type":"stream_event","event":` + e + `}` }
before := `"cache_creation_input_tokens":30,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":10}`
start := `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`
delta := `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`
lines := []string{
ev(`{"type":"message_start","message":{"id":"m1","model":"x","usage":{` + before + `}}}`),
ev(`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"WebSearch"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}`),
ev(`{"type":"message_stop"}`),
`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"results"}]}}`,
ev(`{"type":"message_start","message":{"id":"m2","model":"x","usage":{` + start + `}}}`),
ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"answer"}}`),
ev(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7,` + delta + `}}`),
ev(`{"type":"message_stop"}`),
}
run := &subscriptionRun{}
seg := run.attach()
done := make(chan struct{})
go func() { defer close(done); run.readOutput(strings.NewReader(strings.Join(lines, "\n") + "\n")) }()
var client Usage
for e := range seg {
if e.Kind == KStart || e.Kind == KUsage {
client.add(e.Usage)
}
}
<-done
// told the second message's, billed both: 10 from the first + 5 from
// the second's message_start
if client.CacheWrite1h != 5 || client.billed().CacheWrite1h != 15 {
t.Errorf("1h writes = %d told, %d billed; want 5 and 15", client.CacheWrite1h, client.billed().CacheWrite1h)
}
}