diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 5cbaa953a..4a1c03cd8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -184,7 +184,7 @@ recorded as a prediction failure (`noPrediction`). - A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another. - A refusal that comes as an error (#2400, Jichao). An error whose own `message` is, whole, `The request was rejected because it was considered high risk` is a refusal with no code beside it (`highRiskRefusal` in `policyRefusal`): in an HTTP error body or a stream's error event, never in an answer's text, which may quote it. The vendor that sends it isn't known; it says the request was turned away, so it goes to the next candidate under `RefusalRetries` like any refusal and rests nobody. A refusal error event before any content ends the try at once (`eventRefusalError`, `stop` as for any error), so an upstream that keeps the stream open doesn't hold the next candidate back; a refusal's stop or finish marker is still read to the end for the usage and terminator after it. After content, every write is read for a late refusal (`refusalAfter`), so one whose `event: error` name and data come in separate writes is still noted, and nothing is replayed. `TestHighRisk*`, `TestRefusalErrorDoesNotWaitForEOF` in [`refusal_error_test.go`](../../internal/gateway/refusal_error_test.go). -- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, as does one whose `chatgpt-account-id` isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another `CODEX_HOME`), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is. +- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (`failedRow` in `serve`, written once the next try begins): a Claude subscription run that failed after Anthropic's `message_start` had written the conversation to that account's cache, and the next account wrote it again, while the Usage page counted the second alone (hhxk233 and Kayrainforest on X; `relay` keeps the reply start's usage on a failure, `TestClaudeSubscriptionFailedTryKeepsItsTokens`). A try that failed before anything was billed has no record; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, as does one whose `chatgpt-account-id` isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another `CODEX_HOME`), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is. - Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. diff --git a/internal/gateway/claude_failed_try_usage_test.go b/internal/gateway/claude_failed_try_usage_test.go new file mode 100644 index 000000000..769e2250c --- /dev/null +++ b/internal/gateway/claude_failed_try_usage_test.go @@ -0,0 +1,91 @@ +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) + } + }) + } + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 2c38d26a3..327f08bae 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -5864,6 +5864,14 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name msg = head[n-1].Text } abort() + // what Anthropic said the reply's start used, the conversation + // written to the account's cache, is the failed try's, kept + // with its row when the request goes on to another (serve) + for _, ev := range head { + if ev.Kind == KStart || ev.Kind == KUsage { + usage.add(ev.Usage) + } + } code := 502 if n > 0 { usage.add(Usage{ErrType: head[n-1].Code, RequestID: head[n-1].RequestID}) @@ -5929,7 +5937,9 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name } if col.err != "" && !saidAnything(col.res.Parts) { abort() - // a status, as in a stream, so another account can take over + // a status, as in a stream, so another account can take over; + // what the reply's start used is the failed try's + usage.add(col.res.Usage) usage.add(Usage{ErrType: col.errCode}) code, msg := bridgeFailed(name, col.err, col.errStatus) return writeError(w, from, code, name+": "+msg), msg diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 36294888c..1626cf758 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2861,7 +2861,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // the plan as it stands for the tries: whether the one that answers // stood in for a member listed ahead of its own (standsInFor) plannedCs, plannedOrder := slices.Clone(cands), pl.order + // the row of the try before, when it failed, billed something and + // handed the request on, written once the next try begins + var failedRow func() for i := 0; i < len(cands); i++ { + if failedRow != nil { + failedRow() + failedRow = nil + } c := cands[i] if j := s.laneMate(cands, i, isGroup, gaveWay); j > i { // its key or account is full, and another of its provider's, @@ -3418,6 +3425,38 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if try.FirstReasoning > 0 { call.FirstReasoning = sinceStart(began.Sub(start), hw.first.reasoning) } + // A try that fails from here and hands the request on, to another + // account or member or the same one again, is in the ledger with + // what its vendor billed for it, as a refusal's is: a Claude + // subscription run that failed after Anthropic began its reply had + // written the whole conversation to that account's cache, and the + // next account wrote it again, while the Usage page counted the + // second alone, "2 tries" the only sign of the first (hhxk233 and + // Kayrainforest on X). A failure that billed nothing has no row. + failedRow = func() { + if call.To == "" { + return + } + u := call.Usage.billed() + if u.Input+u.Output+u.CacheRead+u.CacheWrite == 0 { + return + } + rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model, + ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, + Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, + Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, + CacheWrite: u.CacheWrite, CacheWrite1h: u.CacheWrite1h, CacheUnknown: u.cacheNotCounted(), Reasoning: u.Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status, + TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, + TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, + RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true} + failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) + failed := &Call{RequestBody: call.RequestBody, RequestTruncated: call.RequestTruncated, ResponseBody: string(hw.errBody()), maskIn: call.maskIn} + if call.wholeIn != nil { + failed.wholeIn, failed.wholeOut = call.wholeIn, hw.errBody() + } + withBodies(&rec, failed) + appendUsage(r, rec) + } sentMs, ownMs, retriedMs, queuedMs = 0, 0, 0, 0 if at := wrote.Load(); at > 0 && call.TTFT > 0 { sentMs = min(max(time.Unix(0, at).Sub(start).Milliseconds(), 1), call.TTFT) @@ -3634,6 +3673,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro withBodies(&rec, refusal) appendUsage(r, rec) } + failedRow = nil // its row is written continue } if !last && hw.failed() && hw.turnedAway { @@ -3678,6 +3718,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro withBodies(&rec, refusal) appendUsage(r, rec) } + failedRow = nil // its row is written continue } if !last && hw.failed() && promptRefused(hw.code(), hw.errBody()) {