Files
magpie/internal/gateway/claude_failed_try_usage_test.go
T
yetone d2a83de612 gateway: a try billed before it failed and handed on keeps its usage row
A Claude subscription run that fails after Anthropic's message_start
(an overload, a dropped connection, a cut stream Claude Code gave up on)
is a 502 so another account can take over. That account is a new Claude
Code told the whole conversation, and writes it to its own cache again.
The first try's usage was dropped twice over: relay threw away the reply
start's usage on that path, and serve wrote a usage row only for the
request's last try (and for refusals). The Usage page counted the second
account's tokens alone, with "2 tries" on the row as the only sign that
the conversation went out twice (hhxk233 and Kayrainforest on X).

- relay keeps the usage of the head's KStart/KUsage events on a failure
  before content (streamed), and the collector's usage (not streamed).
- serve writes a handed_on row for any failed try that billed something
  and handed the request on, to another account or member or the same
  one again. The row is written when the next try begins. The refusal
  and turned-away paths keep their own row, and a failure that billed
  nothing still has none. Totals count a handed_on row's tokens, not a
  request, as for refusals. The Usage page already shows such a row as
  "<status> · handed on" with its tooltip in every language.

No same-account double send was found: a fake Claude Code breaking its
stream in nine ways (error before or after message_start, a 529 or 500
result, a cut then an error or an exit, text then an error or an exit),
streamed and not, starts one run per account at most. A failure before
content goes on to the spare once. A failure after text ends the
request with no other run.

Run, at this tree on origin/main de7953e3b:
- mote: go test ./internal/gateway -run 'TestClaudeSubscriptionFailedTryKeepsItsTokens|TestClaudeSubscriptionRefusal|TestClaudeSubscriptionBigRefusal' ok;
  -run 'Retried|SearchInstead|HandedOn|Refus|Loop' ok (25.5s); gofmt -l clean.
- The full suite (go test -tags nogui -timeout 45m ./..., Linux, wsl-run)
  was still running at push time. mote had other sessions' suites the
  whole hour. Its result goes in a follow-up if it shows a red.
Broken by hand: with the failedRow() call commented out, the new test is
red ("handed-on rows: []", both stream modes). With relay's change alone
missing, it was red the same way.
Not tried: real Claude Code against a mock Anthropic that cuts the
stream. Claude Code's own stream-to-non-stream fallback (strings in
2.1.316) resends inside one run. magpie's ledger can't see that, and it
happens the same without magpie.
2026-11-02 03:38:42 +08:00

92 lines
3.3 KiB
Go

package gateway
import (
"encoding/json"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/usage"
)
// A Claude subscription run that fails after Anthropic began its reply,
// its message_start's 90K written to the first account's cache, and the
// spare account answering the same request: the ledger has the first
// try's row too, with what it billed, marked as handed on, beside the
// request's own row. The Usage page counted the second alone, its "2
// tries" the only sign that the whole conversation went to two accounts
// (hhxk233 and Kayrainforest on X). A try that failed before anything was
// billed has no row.
func TestClaudeSubscriptionFailedTryKeepsItsTokens(t *testing.T) {
start := ` echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m1","model":"claude-sonnet-5","usage":{"input_tokens":3,"cache_creation_input_tokens":90000}}}}'
`
failed := ` echo '{"type":"result","subtype":"success","is_error":true,"api_error_status":529,"result":"API Error: 529 overloaded"}'
`
for _, billed := range []bool{true, false} {
for _, stream := range []bool{true, false} {
t.Run(fmt.Sprintf("billed=%v/stream=%v", billed, stream), func(t *testing.T) {
first := failed
if billed {
first = start + failed
}
log := claudeSubscriptionFirstSays(t, first)
s := New()
body, _ := json.Marshal(map[string]any{"model": "claude/claude-sonnet-5", "max_tokens": 50, "stream": stream,
"messages": []map[string]any{{"role": "user", "content": "ping"}}})
code, reply := sendTo(s, "/v1/messages", string(body))
b, _ := os.ReadFile(log)
if code != 200 || !strings.Contains(reply, "pong") || strings.Join(strings.Fields(string(b)), ",") != "own,tok-spare" {
t.Fatalf("status %d: %s (runs %q)", code, reply, b)
}
route := lastRoute(s).ID
var rows []usage.Record
deadline := time.Now().Add(10 * time.Second)
for {
rows = rows[:0]
for _, u := range usage.Load(time.Time{}) {
if u.RouteID == route {
rows = append(rows, u)
}
}
if len(rows) >= 1 && rows[len(rows)-1].ProviderAccount == "spare@example.com" || time.Now().After(deadline) {
break
}
time.Sleep(20 * time.Millisecond)
}
var answered, handed []usage.Record
for _, u := range rows {
if u.HandedOn {
handed = append(handed, u)
} else {
answered = append(answered, u)
}
}
if len(answered) != 1 || answered[0].ProviderAccount != "spare@example.com" || answered[0].Tries != 2 || answered[0].Status != 200 {
t.Fatalf("the request's row: %+v", answered)
}
if !billed {
if len(handed) != 0 {
t.Fatalf("a try that billed nothing has a row: %+v", handed)
}
return
}
if len(handed) != 1 {
t.Fatalf("handed-on rows: %+v", handed)
}
h := handed[0]
if h.ProviderAccount != "me@example.com" || h.CacheWrite != 90000 || h.Input != 3 || h.Status != 529 || h.Tries != 0 {
t.Fatalf("the first try's row: account %q, in %d, cache write %d, status %d, tries %d",
h.ProviderAccount, h.Input, h.CacheWrite, h.Status, h.Tries)
}
// one request, its tokens both tries'
tot := usage.NewPricer()(rows)
if tot.Calls != 1 || tot.Errors != 0 || tot.Retried != 1 || tot.CacheWrite != 90000 {
t.Fatalf("totals: %+v", tot)
}
})
}
}
}