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/mainca77a9ea8: 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)
93 lines
4.0 KiB
Go
93 lines
4.0 KiB
Go
package gateway
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestCachePartialUpdateMatrix(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name, fields string
|
|
hour int
|
|
}{
|
|
{"A_zeroFilled", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 15},
|
|
{"B_partial5m", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":0}`, 15},
|
|
{"C_partialBoth", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":2}`, 12},
|
|
{"D_partial1h", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2}`, 12},
|
|
{"E_pure5m", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":0}`, 15},
|
|
{"F_pure1h", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20}`, 30},
|
|
{"G_unreported", `"cache_creation_input_tokens":20`, 15},
|
|
{"H_zeroTotal", `"cache_creation_input_tokens":0`, 15},
|
|
{"I_zeroTotalSplit", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 15},
|
|
{"J_noCache", `"output_tokens":7`, 15},
|
|
{"K_splitOnly", `"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`, 15},
|
|
{"L_consistent", `"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":5}`, 15},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
delta := `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{` + tc.fields + `}}`
|
|
t.Run("bridge", func(t *testing.T) { checkCacheBridge(t, delta, tc.hour) })
|
|
t.Run("continuation", func(t *testing.T) { checkCacheContinuation(t, delta, tc.hour) })
|
|
t.Run("search", func(t *testing.T) { checkCacheSearch(t, delta, tc.hour) })
|
|
})
|
|
}
|
|
}
|
|
|
|
func checkCacheBridge(t *testing.T, delta string, hour int) {
|
|
t.Helper()
|
|
ev := func(e string) string { return `{"type":"stream_event","event":` + e + `}` }
|
|
lines := []string{
|
|
ev(cacheSplitRoundStart(zeroSplitBefore)),
|
|
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(cacheSplitRoundStart(zeroSplitStart)),
|
|
ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"answer"}}`),
|
|
ev(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
|
|
if client.CacheWrite != 20 || client.CacheWrite1h != hour-zeroSplitBefore1h {
|
|
t.Errorf("client writes: %d/hour%d, want the last message's 20/hour%d", client.CacheWrite, client.CacheWrite1h, hour-zeroSplitBefore1h)
|
|
}
|
|
if b := client.billed(); b.CacheWrite != 50 || b.CacheWrite1h != hour {
|
|
t.Errorf("billed writes: %d/hour%d, want50/hour%d", b.CacheWrite, b.CacheWrite1h, hour)
|
|
}
|
|
}
|
|
|
|
func TestCacheZeroFilledPartialUpdateOmitsSplit(t *testing.T) {
|
|
before := Usage{CacheWrite: 30, CacheWrite1h: 10}
|
|
for _, tc := range []struct {
|
|
name string
|
|
total int
|
|
}{
|
|
{"positiveTotal", 20},
|
|
{"zeroTotal", 0},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
u := aUsage{CacheCreationInputTokens: tc.total, CacheCreation: &aCacheCreation{}}.usage().plus(before, true)
|
|
got := u.anthropic().CacheCreation
|
|
if tc.total > 0 {
|
|
if got != nil {
|
|
t.Fatalf("zero-filled partial update rendered split %+v, want none", got)
|
|
}
|
|
} else if got == nil || *got != (aCacheCreation{}) {
|
|
t.Fatalf("zero-total split = %+v, want reported zero split", got)
|
|
}
|
|
})
|
|
}
|
|
}
|