diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 903e74c32..4262910e8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -185,6 +185,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`; 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. +- A failed call is in `app.log` too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). `record` writes each call whose status is 400 or more, or that carries an error, as one line (`failedCallLine`: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (`failedLogEvery`), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (`codexEndedEarly` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as `response.failed`, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (`srv.Shutdown`'s error; on Windows there is no handover, so an update or quit cuts a stream after `shortDrain`) (`TestCodexReplyBrokenOffLogged`, `TestCodexClientGoneLogged`, `TestFailedCallLineOncePerMinute`). - 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/codex_backend.go b/internal/gateway/codex_backend.go index d4ee23c3c..42768883c 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1150,7 +1150,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st } var sniff *usageSniffer var refusal []byte // what OpenAI said, of a request it turned away - relayedAcct := "" // magpie's ChatGPT account the turn went out on, if any + // how the last try's reply ended, for the log of one that ended early + // (codexEndedEarly): the read of OpenAI's that failed, the write to + // the client that did, and the bytes it was passed + var readErr, writeErr error + var passed int64 + relayedAcct := "" // magpie's ChatGPT account the turn went out on, if any if rest == "/responses" && base != codexAPIBase { // the account goes on its credits, its week used up: a reset it // spends by itself when the week runs out goes first @@ -1411,8 +1416,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st f, _ := out.(http.Flusher) buf := make([]byte, 32<<10) refusal = nil + readErr, writeErr, passed = nil, nil, 0 for { n, err := res.Body.Read(buf) + if err != nil && err != io.EOF { + readErr = err + } if n > 0 { if captureTitle { titleReply.add(buf[:n]) @@ -1425,7 +1434,10 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st if res.StatusCode >= 400 && len(refusal) < 8<<10 { refusal = append(refusal, buf[:n]...) } - if _, werr := out.Write(buf[:n]); werr != nil { + m, werr := out.Write(buf[:n]) + passed += int64(m) + if werr != nil { + writeErr = werr break } if f != nil { @@ -1512,6 +1524,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st w.Write([]byte("\n\n")) streamError(w, provider.Responses, call.Model, call.Status, said) } + if line := codexEndedEarly(res, sniff, call.Model, callerOf(r).agent, began, passed, readErr, writeErr, r.Context()); line != "" { + log.Print(line) + } end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output) call.Route = tr.ID call.Masked = s.trace.maskedOf(tr) @@ -1830,6 +1845,51 @@ func codexStreamCut(res *http.Response, sniff *usageSniffer, began time.Time, ct "The reply is lost, and asking again sends the turn whole" } +// codexEndedEarly is the app.log line of a relayed Codex stream that +// ended before its last event, "" for one that came whole or failed with +// a status: which side ended it, and how. Codex says only what its HTTP +// client says of a connection that broke under a reply, "error decoding +// response body" (reqwest's words for any failed read of a body), so the +// log tells a reply OpenAI broke off (its read's error, or a clean end +// before response.completed) from a client that went away or couldn't be +// written to (wjh66 on Discord: "reconnecting 5/5", then that error, and +// nothing in app.log). +func codexEndedEarly(res *http.Response, sniff *usageSniffer, model, agent string, began time.Time, passed int64, readErr, writeErr error, ctx context.Context) string { + if res == nil || sniff == nil || res.StatusCode >= 400 { + return "" + } + if sniff.sse && sniff.whole() { + return "" + } + // a body not a stream's has no last event to miss: only a read or a + // write that failed, or a client gone, ended it early + if !sniff.sse && readErr == nil && writeErr == nil && ctx.Err() == nil { + return "" + } + agent = cmp.Or(agent, "the client") + upstream := "OpenAI ended the stream" + if readErr != nil { + upstream = "reading OpenAI's stream failed (" + readErr.Error() + ")" + } + var client string + switch { + case writeErr != nil: + client = "writing to " + agent + " failed (" + writeErr.Error() + ")" + case ctx.Err() != nil: + client = agent + " went away (" + context.Cause(ctx).Error() + ")" + case sniff.failed != "": + client = agent + " was passed OpenAI's failure" + default: + client = agent + " was told it as response.failed" + } + before := "before its last event" + if !sniff.sse { + before = "before its end" + } + return fmt.Sprintf("gateway: codex: the reply of %s ended %s in, %s, %d bytes passed on: %s; %s", + cmp.Or(model, "(no model)"), time.Since(began).Round(time.Millisecond), before, passed, upstream, client) +} + // routeOf is the id of the route a Codex relay opened, so the call it // records is the one the Routing page's "Request and response" opens (#2481); // 0 for a compaction, which opens none. diff --git a/internal/gateway/codex_ended_early_test.go b/internal/gateway/codex_ended_early_test.go new file mode 100644 index 000000000..df63e0cd6 --- /dev/null +++ b/internal/gateway/codex_ended_early_test.go @@ -0,0 +1,210 @@ +package gateway + +import ( + "bufio" + "bytes" + "io" + "log" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// lockedLog is the standard logger's output for a test, safe to read +// while the gateway's goroutines write it. +type lockedLog struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (l *lockedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +func (l *lockedLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.String() +} + +func catchLog(t *testing.T) *lockedLog { + t.Helper() + l := &lockedLog{} + old := log.Writer() + log.SetOutput(l) + t.Cleanup(func() { log.SetOutput(old) }) + return l +} + +// waitLogged waits for the log to have a line holding every one of want. +func waitLogged(t *testing.T, l *lockedLog, want ...string) string { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for { + for _, line := range strings.Split(l.String(), "\n") { + all := true + for _, w := range want { + all = all && strings.Contains(line, w) + } + if all { + return line + } + } + if time.Now().After(deadline) { + t.Fatalf("no log line holds %q; the log:\n%s", want, l.String()) + } + time.Sleep(10 * time.Millisecond) + } +} + +func codexUpstreamAt(t *testing.T, h http.HandlerFunc) { + t.Helper() + codexSignedIn(t) + up := httptest.NewServer(h) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-6.1-sol"}}); err != nil { + t.Fatal(err) + } +} + +// wjh66 on Discord (0.1.2696, Windows): a Codex turn on gpt-6.1-sol showed +// "reconnecting 5/5", then "error decoding response body" — reqwest's +// words for a body whose connection broke while it was read — and app.log +// had nothing of the turn. The ChatGPT backend's connection broken off +// inside a chunk, as a reset does, reaches Codex as a whole HTTP reply +// whose stream says it failed (no broken body of magpie's for Codex to +// fail to decode), and app.log says which side ended it and how. +func TestCodexReplyBrokenOffLogged(t *testing.T) { + logs := catchLog(t) + codexUpstreamAt(t, func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + conn, rw, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + defer conn.Close() + events := sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_text.delta","delta":"half a reply"}`) + // no Content-Type, as the ChatGPT backend streams; a chunk + // promised longer than what comes, and the connection closed + rw.WriteString("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n") + rw.WriteString(strconv.FormatInt(int64(len(events)+64), 16) + "\r\n" + events) + rw.Flush() + }) + server := httptest.NewServer(New().Handler()) + defer server.Close() + req, _ := http.NewRequest("POST", server.URL+CodexPath+"/responses", + strings.NewReader(`{"model":"gpt-6.1-sol","stream":true,"input":"hi"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "codex_cli_rs/0.160.0 (Windows 10.0.26100; x86_64)") + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + body, err := io.ReadAll(res.Body) + if err != nil { + t.Fatalf("magpie's reply broke off under the client (Codex: error decoding response body): %v\n%s", err, body) + } + if !strings.Contains(string(body), "half a reply") || !strings.Contains(string(body), "response.failed") { + t.Fatalf("the reply's delta and its failure weren't both passed on:\n%s", body) + } + line := waitLogged(t, logs, "gateway: codex:", "gpt-6.1-sol", "reading OpenAI's stream failed", "before its last event") + if !strings.Contains(line, "told it as response.failed") { + t.Fatalf("the line doesn't say what the client was told: %s", line) + } + waitLogged(t, logs, "gpt-6.1-sol", "failed: 502", "before its last event") +} + +// The other side: the client going away mid-reply (Codex's own timeout, a +// proxy between them, a window closed) is logged as the client's end, so +// a report of a broken reply tells the leg it broke on. +func TestCodexClientGoneLogged(t *testing.T) { + logs := catchLog(t) + codexUpstreamAt(t, func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_text.delta","delta":"half a reply"}`)) + w.(http.Flusher).Flush() + // the reply goes on until magpie lets go of it: a write to the + // client that left is how magpie learns it did + for { + select { + case <-r.Context().Done(): + return + case <-time.After(20 * time.Millisecond): + } + io.WriteString(w, sse(`data: {"type":"response.output_text.delta","delta":" more"}`)) + w.(http.Flusher).Flush() + } + }) + server := httptest.NewServer(New().Handler()) + defer server.Close() + tr := &http.Transport{} + defer tr.CloseIdleConnections() + req, _ := http.NewRequest("POST", server.URL+CodexPath+"/responses", + strings.NewReader(`{"model":"gpt-6.1-sol","stream":true,"input":"hi"}`)) + req.Header.Set("Content-Type", "application/json") + res, err := (&http.Client{Transport: tr}).Do(req) + if err != nil { + t.Fatal(err) + } + br := bufio.NewReader(res.Body) + for { + l, err := br.ReadString('\n') + if err != nil { + t.Fatalf("the delta never came: %v", err) + } + if strings.Contains(l, "half a reply") { + break + } + } + res.Body.Close() // the connection with it: the client is gone + waitLogged(t, logs, "gateway: codex:", "gpt-6.1-sol", "before its last event", "went away") +} + +// The same failure over and over is logged once a minute, with how many +// times it came in between. +func TestFailedCallLineOncePerMinute(t *testing.T) { + failedLog.Lock() + failedLog.last = nil + failedLog.Unlock() + c := Call{Agent: "codex", Model: "gpt-6.1-sol", Provider: "openai", Status: 502, Millis: 1200, Error: "OpenAI closed the stream"} + now := time.Date(2026, 11, 2, 15, 27, 0, 0, time.UTC) + line, ok := failedCallLine(c, now) + if !ok || !strings.Contains(line, "codex's call to gpt-6.1-sol on openai failed: 502 after 1.2s: OpenAI closed the stream") { + t.Fatalf("first failure: %v %q", ok, line) + } + for i := range 3 { + if _, ok := failedCallLine(c, now.Add(time.Duration(i+1)*time.Second)); ok { + t.Fatal("the same failure was logged again within the minute") + } + } + other := c + other.Status = 499 + if _, ok := failedCallLine(other, now.Add(time.Second)); !ok { + t.Fatal("another failure was held with the first") + } + line, ok = failedCallLine(c, now.Add(time.Minute+time.Second)) + if !ok || !strings.Contains(line, "and 3 times more like it") { + t.Fatalf("after the minute: %v %q", ok, line) + } + if _, ok := failedCallLine(Call{Status: 200, Model: "x"}, now); ok { + t.Fatal("a call that didn't fail was logged") + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index beb3b360d..9dcd2e218 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -611,9 +611,70 @@ func (s *Server) record(c Call) { s.recent = keepRecent(s.recent, c) if s.debug { log.Printf("%s %s → %s (%s→%s) %d %dms %s", c.Model, c.Provider, c.Provider, c.From, c.To, c.Status, c.Millis, c.Error) + } else if line, ok := failedCallLine(c, time.Now()); ok { + log.Print(line) } } +// failedCallLine is the app.log line of a call that failed: its status, +// or a 200 whose reply was cut, canceled or failed on its stream. Every +// failure was the Routing page's and the usage ledger's alone, so a +// report that came with app.log had no trace of it (wjh66 on Discord: +// Codex's "error decoding response body" after "reconnecting 5/5", and +// nothing in the log about the turns). The same failure again within +// failedLogEvery is counted, not logged again, so a client asking in a +// loop can't fill the log. +func failedCallLine(c Call, now time.Time) (string, bool) { + if c.Status < 400 && c.Error == "" { + return "", false + } + said := c.Error + if r := []rune(said); len(r) > 300 { + said = string(r[:300]) + "…" + } + key := c.Agent + "|" + c.Provider + "|" + c.Model + "|" + strconv.Itoa(c.Status) + "|" + said + failedLog.Lock() + defer failedLog.Unlock() + if failedLog.last == nil { + failedLog.last = map[string]failedSeen{} + } + seen := failedLog.last[key] + if !seen.at.IsZero() && now.Sub(seen.at) < failedLogEvery { + seen.skipped++ + failedLog.last[key] = seen + return "", false + } + if len(failedLog.last) >= 256 { + for k, v := range failedLog.last { + if now.Sub(v.at) >= failedLogEvery { + delete(failedLog.last, k) + } + } + } + failedLog.last[key] = failedSeen{at: now} + agent := cmp.Or(c.Agent, "a client") + line := fmt.Sprintf("gateway: %s's call to %s on %s failed: %d after %s: %s", + agent, cmp.Or(c.Model, "(no model)"), cmp.Or(c.Provider, "(none)"), c.Status, + (time.Duration(c.Millis) * time.Millisecond).Round(time.Millisecond), cmp.Or(said, "(nothing said)")) + if seen.skipped > 0 { + line += fmt.Sprintf(" (and %d times more like it since the last line)", seen.skipped) + } + return line, true +} + +// failedLogEvery is how often the same failure is logged at most. +const failedLogEvery = time.Minute + +type failedSeen struct { + at time.Time + skipped int +} + +var failedLog struct { + sync.Mutex + last map[string]failedSeen +} + // recentMost is how many calls the Recent-calls ring keeps. const recentMost = 40 @@ -787,7 +848,12 @@ func (s *Server) ListenAndServe(ctx context.Context) error { // Shutdown doesn't wait for it: each ends after its turn in flight sockets := make(chan struct{}) go func() { defer close(sockets); s.sockets.drain(c) }() - srv.Shutdown(c) + if err := srv.Shutdown(c); err != nil { + // the requests still answering are cut where they are, and + // an agent streaming one reads a reply broken off (Codex: + // "error decoding response body") + log.Printf("gateway: ending after %s with requests still in flight; they are cut (%v)", s.drainFor(), err) + } <-sockets s.subscription.abortAll() provider.FlushServed() // what answered last, kept for the next start and the CLI