gateway: the ChatGPT backend's "auto"/"default" tier is recorded as unknown (jjt on Discord)

The ChatGPT Codex backend says service_tier "auto" in response.created
and "default" in response.completed whether priority ran or not. jjt's
measurements on gpt-6.1-sol with a Plus account: Fast decodes at about
200 tok/s, without it about 110, and the reply says "default" both times
(real-priority.sse, speed-plus.txt). magpie copied that into tier_served,
so the usage log, its CSV and /v1/magpie/route said served = default for
requests that ran Fast.

servedTierAt (tier_record.go) leaves those two words empty when the
reply came from CodexBase's host. It is applied once per routed try, in
attempt (gateway.go, a defer, so every return path and the route's tries
see it), and on the relay of Codex's own sign-in (codexUpstreamOn).
OpenAI's API, where service_tier means what it says, keeps it as given:
a provider at api.openai.com and Codex with an sk- key relayed to it.
"priority" or "ultrafast" said by the ChatGPT backend is still kept.

Display: tier_served is shown by the CSV (an empty cell), the JSON log
and /v1/magpie/route (omitempty). No GUI page or TUI shows a tier
(grep of internal/gui/assets and internal/tui for tier_served,
tier_asked, tierServed: none), so no strings changed. docs/reference.md
and docs/subsystems/gateway-routing.md say it.

Tests:
- TestChatGPTBackendTierUnknown (new): the backend says auto, then
  default (jjt's events, cut to the fields read); a routed try asked
  priority and one asked nothing, and Codex's own sign-in relayed, all
  record "" in usage and the route.
- TestOpenAIAPITierKept (new): api.openai.com's "priority" and
  "default" kept, routed and through the sk- relay.
- TestTierRecordedPerTry: its "none asked" case on the ChatGPT backend
  now expects "" where it expected "default".

Run on mote (mote-run; the wider run at base cc81ad4ea, the tier run
again after the rebase, at this commit on c37b8b659: ok, 22 pass):
- go test ./internal/gateway -run 'Tier|ChatGPTBackend|OpenAIAPI'
  -count=1 -v: ok, 22 tests pass.
- go test ./internal/usage: ok. go test ./internal/gateway -run
  'Codex|Usage|Route|Tier': two reds, TestAntigravityTurnsCodexs-
  GPT5ThreadAwayOnce and TestCodexSpentGrokFailingIsTold, red the same
  on a fresh origin/main c37b8b659 and filed as #4362; the rest ok.
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean.
- gofmt -l internal/gateway: clean.
Broken by hand: servedTierAt returning t unchanged -> TestChatGPT-
BackendTierUnknown and TestTierRecordedPerTry red ("served default");
the host check removed -> TestOpenAIAPITierKept red (served "", want
"default"). Both green again with the fix.

Not tried: a real ChatGPT account through the built gateway; the full
Go suite (the coordinator asked for the targeted run under mote's load
of ~200); Windows and Linux test runs (vet only). No GUI file reads the
tier, so no GUI test was run.
This commit is contained in:
yetone
2026-10-30 13:57:36 +08:00
parent c37b8b6594
commit dafe4af822
7 changed files with 173 additions and 10 deletions
+3 -1
View File
@@ -421,7 +421,9 @@ service tier the client asked for (Claude's fast speed reads `fast`), the
one that try went out at (a fast pick sends `priority`, or `ultrafast`
where the pick is set to Ultrafast; Ultrafast becomes
`priority` on an account whose plan doesn't offer it), and the one the
vendor's reply said it ran at, empty when the reply doesn't say. The JSON
vendor's reply said it ran at, empty when the reply doesn't say. The
ChatGPT backend (Codex signed in with ChatGPT) says `auto` and `default`
whether Fast ran or not, so from it those are left empty too. The JSON
log keeps them as `tier_asked`, `tier_sent` and `tier_served`, and each
try in `/v1/magpie/route` has `tier` and `tier_served`. The last column,
`upstream_stop`, is why the upstream said its reply ended, in its own
+1 -1
View File
@@ -179,7 +179,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.
- 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. 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).
- 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`.
- What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic `cache_read_input_tokens` and `cache_creation_input_tokens`, DeepSeek's `prompt_cache_hit_tokens` or Moonshot's top-level `cached_tokens` beside a 0 in `prompt_tokens_details`) is told in OpenAI's too, streamed (`chatTidy`) and whole (`chatWhole`), by `openAIUsage` in [`chattidy.go`](../../internal/gateway/chattidy.go): `prompt_tokens_details.cached_tokens` (and `cache_write_tokens`), with `prompt_tokens` and `total_tokens` made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (`mayMendUsage`). pi-ai, which DeepSeek Harness and Pi use, reads `prompt_tokens_details.cached_tokens` first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. `TestAgentReadsCacheTokensOnEveryRoute`, `TestPluginAgentReadsCacheTokens`, `TestOpenAIUsageLeavesOpenAIsAlone`, `TestMayMendUsageOnlyOtherNames` in [`usage_cache_agent_test.go`](../../internal/gateway/usage_cache_agent_test.go).
+1
View File
@@ -1455,6 +1455,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
call.TTFT, call.FirstText = first.ms()
call.ReasoningHidden = first.hidesReasoning(provider.Responses)
uu.add(sniff.usage())
uu.Tier = servedTierAt(provider.HostOf(base), uu.Tier)
call.Flow = first.flowFor(uu.Reasoning)
call.Usage, served = uu, uu.Served
errType := ""
+3
View File
@@ -4094,6 +4094,9 @@ func sinceStart(before, d time.Duration) int64 {
// attempt sends a request to one provider. call.To stays empty when the
// provider has no endpoint to send it to.
func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, call *Call) (int, string) {
// the tier the reply said, unknown where the vendor's word tells
// nothing (servedTierAt)
defer func() { call.Usage.Tier = servedTierAt(p.Host(), call.Usage.Tier) }()
// Normalize for the actual destination, separately on each fallback.
// Native ChatGPT accounts accept standalone tool outputs themselves.
if from == provider.Responses && (p.Account == nil || p.Account.Agent != "codex") {
+15 -8
View File
@@ -27,8 +27,10 @@ import (
// offer gpt-6-luna's Ultrafast only to the Pro account. It returns the
// account and service tier each request was tried with, in order. With
// echo set, a reply says the tier it ran at, as OpenAI's API does
// (service_tier on the response: the one asked, or "default").
func tierAccounts(t *testing.T, proOut, echo *bool) func() []string {
// (service_tier on the response: the one asked, or "default"). With said
// given, response.created and response.completed say the tiers it gives
// for the one asked.
func tierAccounts(t *testing.T, proOut, echo *bool, said ...func(asked string) (created, completed string)) func() []string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
@@ -81,14 +83,18 @@ func tierAccounts(t *testing.T, proOut, echo *bool) func() []string {
io.WriteString(w, `{"error":{"message":"You've hit your usage limit"}}`)
return
}
said := ""
began, ended := "", ""
if echo != nil && *echo {
said = `,"service_tier":"` + cmp.Or(q.Tier, "default") + `"`
ended = `,"service_tier":"` + cmp.Or(q.Tier, "default") + `"`
}
if len(said) > 0 {
c, d := said[0](q.Tier)
began, ended = `,"service_tier":"`+c+`"`, `,"service_tier":"`+d+`"`
}
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"}}`,
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"`+began+`}}`,
`data: {"type":"response.output_text.delta","delta":"pong"}`,
`data: {"type":"response.completed","response":{"id":"r1"`+said+`,"usage":{"input_tokens":7,"output_tokens":1}}}`))
`data: {"type":"response.completed","response":{"id":"r1"`+ended+`,"usage":{"input_tokens":7,"output_tokens":1}}}`))
}))
t.Cleanup(up.Close)
old := provider.CodexBase
@@ -277,12 +283,13 @@ func TestTierRecordedPerTry(t *testing.T) {
if sr := sessionRouteOf(r); sr.Tier != "ultrafast" || sr.TierServed != "ultrafast" {
t.Errorf("route: %+v", sr)
}
// none asked: none in the log, and the reply's "default" as it said
// none asked: none in the log, and the ChatGPT backend's "default"
// kept as unknown, which it is there (servedTierAt)
postFrom(t, s, "omp", "/v1/responses", `{"model":"codex/gpt-6-luna","input":"ping"}`)
tried()
recs = usage.Load(time.Time{})
if n := len(recs); n < 3 || recs[n-2].TierAsked != "ultrafast" || recs[n-2].TierSent != "ultrafast" || recs[n-2].TierServed != "ultrafast" ||
recs[n-1].TierAsked != "" || recs[n-1].TierSent != "" || recs[n-1].TierServed != "default" {
recs[n-1].TierAsked != "" || recs[n-1].TierSent != "" || recs[n-1].TierServed != "" {
t.Fatalf("usage: %+v", recs)
}
+136
View File
@@ -0,0 +1,136 @@
package gateway
import (
"cmp"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// jjt on Discord: the ChatGPT backend says "auto" in response.created and
// "default" in response.completed whether priority ran or not (a Plus
// account's Fast turn on gpt-6.1-sol decoded at ~200 tok/s, one without at
// ~110, both "default"). The served tier is kept unknown there, on a
// routed try and on Codex's own sign-in relayed, never as "default". The
// events are jjt's real-priority.sse's, cut to the fields read.
func TestChatGPTBackendTierUnknown(t *testing.T) {
proOut := false
tried := tierAccounts(t, &proOut, nil, func(string) (string, string) { return "auto", "default" })
to, _ := url.Parse(provider.CodexBase)
provider.CodexBase = "https://chatgpt.com/backend-api/codex"
s := New()
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
return http.DefaultTransport.RoundTrip(r)
})}
last := func() usage.Record {
t.Helper()
recs := usage.Load(time.Time{})
if len(recs) == 0 {
t.Fatal("no usage")
}
return recs[len(recs)-1]
}
for _, tier := range []string{"priority", ""} {
ask := `{"model":"codex/gpt-6-luna","input":"ping"}`
if tier != "" {
ask = `{"model":"codex/gpt-6-luna","input":"ping","service_tier":"` + tier + `"}`
}
r := postFrom(t, s, "omp", "/v1/responses", ask)
tried()
if sr := sessionRouteOf(r); sr.TierServed != "" || len(sr.Tries) == 0 || sr.Tries[len(sr.Tries)-1].TierServed != "" {
t.Errorf("%q route: %+v", tier, sr)
}
if rec := last(); rec.TierSent != tier || rec.TierServed != "" {
t.Errorf("%q usage: sent %q served %q", tier, rec.TierSent, rec.TierServed)
}
}
// Codex's own sign-in, relayed as it sent it
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-6-luna","stream":true,"input":"ping","service_tier":"priority"}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-plus")
req.Header.Set("User-Agent", "codex_cli_rs/0.160.1")
s.Handler().ServeHTTP(rec, req)
tried()
if got := last(); rec.Code != 200 || got.TierSent != "priority" || got.TierServed != "" {
t.Errorf("codex relay: %d sent %q served %q", rec.Code, got.TierSent, got.TierServed)
}
}
// OpenAI's API means its service_tier: "default" and "priority" are kept
// as it said, from a provider at api.openai.com and from Codex signed in
// with an API key, relayed there.
func TestOpenAIAPITierKept(t *testing.T) {
f := &fake{t: t}
up := setup(t, provider.Responses, f)
f.reply = "" // set per request below
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: "https://api.openai.com/v1"}); err != nil {
t.Fatal(err)
}
to, _ := url.Parse(up.URL)
s := New()
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Host != "api.openai.com" {
t.Errorf("request to %s", r.URL)
}
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
return http.DefaultTransport.RoundTrip(r)
})}
reply := func(tier string) string {
return sse(
`data: {"type":"response.created","sequence_number":0,"response":{"id":"r1","object":"response","status":"in_progress","model":"m1","usage":null,"service_tier":"auto"}}`,
`data: {"type":"response.output_text.delta","delta":"ok"}`,
`data: {"type":"response.completed","sequence_number":9,"response":{"id":"r1","object":"response","status":"completed","model":"m1","usage":{"input_tokens":1,"output_tokens":1},"service_tier":"`+cmp.Or(tier, "default")+`"}}`)
}
last := func() usage.Record {
t.Helper()
recs := usage.Load(time.Time{})
if len(recs) == 0 {
t.Fatal("no usage")
}
return recs[len(recs)-1]
}
for _, c := range []struct{ asked, want string }{{"priority", "priority"}, {"", "default"}} {
f.reply = reply(c.asked)
ask := map[string]any{"model": "fake/m1", "input": "ping", "stream": true}
if c.asked != "" {
ask["service_tier"] = c.asked
}
b, _ := json.Marshal(ask)
r := postFrom(t, s, "omp", "/v1/responses", string(b))
if sr := sessionRouteOf(r); sr.TierServed != c.want {
t.Errorf("%q route: %+v", c.asked, sr)
}
if rec := last(); rec.TierServed != c.want {
t.Errorf("%q usage: served %q, want %q", c.asked, rec.TierServed, c.want)
}
// Codex with an API key, relayed to OpenAI's API
f.reply = reply(c.asked)
ask = map[string]any{"model": "m1", "input": "ping", "stream": true}
if c.asked != "" {
ask["service_tier"] = c.asked
}
b, _ = json.Marshal(ask)
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(string(b)))
req.Header.Set("Authorization", "Bearer sk-test")
req.Header.Set("User-Agent", "codex_cli_rs/0.160.1")
s.Handler().ServeHTTP(rec, req)
if got := last(); rec.Code != 200 || got.TierServed != c.want {
body, _ := io.ReadAll(rec.Body)
t.Errorf("%q codex api key: %d served %q, want %q: %s", c.asked, rec.Code, got.TierServed, c.want, body)
}
}
}
+14
View File
@@ -18,6 +18,20 @@ import (
"github.com/yetone/magpie/internal/provider"
)
// servedTierAt is the served tier a reply from host says, as the log keeps
// it. The ChatGPT backend's (CodexBase's host) "auto", in response.created,
// and "default", in response.completed, are what it says whether priority
// ran or not: on gpt-6.1-sol with a Plus account a Fast turn decoded at
// about 200 tok/s and one without at about 110, both "default" (jjt on
// Discord). There they tell nothing, and are kept as unknown (""), never
// as the default tier. OpenAI's API means them, and they are kept as said.
func servedTierAt(host, t string) string {
if (t == "auto" || t == "default") && host != "" && host == provider.HostOf(provider.CodexBase) {
return ""
}
return t
}
// bodyTier is the service tier a request body in proto asks for, in
// OpenAI's words (service_tier: "priority", "ultrafast", "flex" …);
// Claude's speed "fast" reads as "fast". "" when it asks for none.