Keep reported Anthropic cache_creation splits, including pure-5m replies,
through API and subscription parsing and client output. Only positive
counters replace known usage. Completed sums retain all counters and
split presence.
Across continuation tries, search rounds and internal bridge messages,
partial updates add earlier total writes only with a positive total. A
split with counts and zero 1h keeps the current message's known 1h before
adding earlier messages' usage. A zero-filled or absent split keeps the
per-counter rule. Omit a zero-filled partial split with a positive total
from output; retain a reported zero-total split. Split presence and the
parsed update's own count evidence remain separate.
Yetone's zero-filled bridge probe and matching continuation/search probes
failed at 0c9298d with 10 instead of 15 1h writes. Fable's partial-5m and
pure-5m cases failed at e1de9bc7 in bridge, continuation and both search
modes with the same loss. All pass after the repair. The 12-case matrix
matches main's client totals and 1h counts and continuation/search ledger
counts. A renderer test rejects a fabricated 50/0 split on a sparse delta.
Verified under sandbox HOME, pinned Go caches and nogui: focused race,
Darwin vet ./..., Linux/Windows gateway vet, gofmt and diff checks. Archive
mutations removing current-message carry, bypassing each of three callers,
and restoring the fabricated split each fail behavior assertions. Restored
archive passes. Earlier zero-total, unreported-split and pure-5m cases stay
green. No live-provider check in this repair.
Review (yetone's session, landed from the PR's head c4cf224 and 90cdb2f):
the partial-cache probes go red when carryUpdate is reverted by hand,
and the 12-case matrix gives the same client totals and 1h counts as
main a15e57656. Rebased on 8b84dc902; gofmt clean; GOOS=darwin/linux/windows
go vet -tags nogui ./... clean.
Full suite: set -o pipefail; go test -timeout 45m ./... at the rebased head -> 65 packages ok, internal/gui red only on TestPanelJoinsFullScreenSpaces ("the panel shown doesn't take the keyboard"), red the same without this change, filed as #2450.
158 lines
6.5 KiB
Go
158 lines
6.5 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}`
|
|
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)
|
|
if details["cache_write_tokens"] != 50.0 {
|
|
t.Errorf("client cache writes=%v, want50", 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 != 50 || u.CacheWrite1h != hour {
|
|
t.Errorf("client writes: %d/hour%d, want50/hour%d", u.CacheWrite, u.CacheWrite1h, hour)
|
|
}
|
|
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
|
|
if client.CacheWrite1h != 15 {
|
|
t.Errorf("1h writes = %d, want 15 (10 from the first message + 5 from the second's message_start)", client.CacheWrite1h)
|
|
}
|
|
}
|