From c32b820a91e63f2737aee3eb46700449ecba8dde Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 5 Nov 2026 00:28:02 +0800 Subject: [PATCH] gateway: a "User location is not supported" refusal rests no account, and the next try goes on a new connection (#5182) ggdayup (#5182): Antigravity answered 400 "User location is not supported for the API use." on one kept-alive connection. magpie asked every account after it on that same connection, each was refused the same and rested, and the agent got a 400, while a new connection about 12s later was answered. The refusal is about the edge the connection reached, not about the account. - routing.go: restAfterMarked returns Rest{By: "off", Until: now} for regionRefused, as for zdr and offline, so no account rests and no failure is counted. - upstream_transport.go: regionFresh wraps each of upstreamTransport's three transports (any, draws, uploads), so every request through s.client is covered. It reads the first 8KB of each reply with status >= 400. When those match regionWords, closing the body calls CloseIdleConnections, and a pending flag calls it again before the next request. That flag covers an HTTP/2 connection that still carried another stream when the body closed. - fallback.go: passing() asks the last candidate again (lastRetries, after retryPause), on a new connection, so a user with one account is helped too. - docs/subsystems/gateway-routing.md: a bullet saying all of this, including what it doesn't cover. Tests (region_fresh_test.go, with a fake TLS edge that refuses every request on the first connection it sees and answers on any other): - TestRegionRefusalDropsItsConnection uses the real New() client, over h2 and h1. After a region 400 the next request goes on a new connection and gets 200. A plain 400 INVALID_ARGUMENT keeps its connection. - TestAntigravityRegionRefusalAsksTheNextOnANewConnection: two accounts. The second is asked on a new connection and answers, no account rests, and Tries[0].Rest.By is "off". - TestAntigravityRegionRefusalAsksTheLastAgain: one account. It is asked again on a new connection and answers. - TestRegionRefusalRestsNoAccount: Google's and Antigravity's wordings, two turns each. Both accounts are asked both times, with no rest, no failure counted and no usage re-read. A 500 still rests the account. - TestGroupFailsOverARegionRefusal (#1621) now asserts By "off" and no rest. Run on mote (mote-run): - go test -count=1 -run 'Region' ./internal/gateway/: ok. - go test -race -count=3 -run 'Region' ./internal/gateway/: ok (16.5s). - go vet ./internal/gateway/ for darwin, linux (-tags nogui) and windows, and go build ./... for all three: all ok. - gofmt -l: clean. - Full suite: run after the push, see #5182. Broken by hand, one at a time, each with a real FAIL and then restored: - regionFresh not wrapping the body: DropsItsConnection h2 and h1 region, AsksTheNext and AsksTheLast are red (the second request goes on the refused connection, and the turn gets 400). - restAfterMarked's early return removed: AsksTheNext and RestsNoAccount are red (By backoff, Failures 1). - passing()'s region case removed: AsksTheLast is red (the turn gets 400). Not tried: a real Antigravity account in a refused region. Nothing here can reproduce Google's per-edge refusal. Not covered: an HTTP/2 connection busy with another stream at that moment outlives the close until it is idle. The close also drops other vendors' idle connections, which costs one handshake each. A user who really is in a refused region now gets the refusal about 3s later, after the last candidate's retries. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/fallback.go | 11 +- internal/gateway/region_fallback_test.go | 6 +- internal/gateway/region_fresh_test.go | 264 +++++++++++++++++++++++ internal/gateway/routing.go | 10 + internal/gateway/upstream_transport.go | 96 ++++++++- 6 files changed, 379 insertions(+), 9 deletions(-) create mode 100644 internal/gateway/region_fresh_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c98882913..68a067b81 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -228,6 +228,7 @@ recorded as a prediction failure (`noPrediction`). - A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`. - A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.test.cjs`. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873). +- A refusal of where the request comes from (`regionWords`: Google's 400 "User location is not supported for the API use.", as Antigravity and Code Assist pass it on, and OpenAI's `unsupported_country_region_territory` / "Country, region, or territory not supported"; `regionRefused`) is the network's and the edge's the connection reached, not the account's. It rests no account and counts no failure (`restAfterMarked` returns `Rest.By` `off`, `Until` now), and the next try goes out on a new connection: `regionFresh` (in `upstreamTransport`, around each of its three transports, so under every request the gateway sends through `s.client`) reads the head of each failed reply, and when it matches it closes the transport's idle connections as the body closes and again before the next request (`pending`), so the HTTP/2 or keep-alive connection that drew the refusal isn't reused. The last candidate is asked again `lastRetries` times after `retryPause` (`passing`). Before, every Antigravity account was asked on the one kept-alive connection, each refused the same and rested, and the agent got a 400, while a new connection answered 12 seconds on (#5182, ggdayup; `TestRegionRefusalDropsItsConnection`, `TestAntigravityRegionRefusalAsksTheNextOnANewConnection`, `TestAntigravityRegionRefusalAsksTheLastAgain`, `TestRegionRefusalRestsNoAccount`). Not covered: an HTTP/2 connection carrying another stream at that moment outlives the close until it is idle, and the close drops other vendors' idle connections too (one handshake each). A user who is truly in a refused region gets the refusal after the retries, about 3 seconds later than before. - One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned, and the sign-in not known to be out of its allowance, `provider.CodexUsedUpKnown`, which routes the turn as `codex/` as a restarted Codex's goes) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. The account out of its allowance goes on to the same fallbacks at once, after the credits retry and the automatic reset are looked at (`codexAccountOut`: a quota, credit or rate refusal, as a status or as a stream's failure before any reply, and a 403 `usage_not_included`; never a 401, which Codex renews its sign-in on). Before that, Codex was handed the 429 with its fallbacks unused (adorable_piglet on Discord, `TestCodexOneAccountSpentFallsBack`); with none set it still is (`TestCodexOneAccountSpentNoFallbackRelayed`). Each try is a `HandedOn` usage record and a try in the trace. The reply's `x-codex-*` windows are kept as the sign-in's usage and a `usage_limit_reached` refusal has it read again at once (`heardCodexLimits`, `codexMayBeUsedUp`), as on the accounts path. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)). - A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before. - A ChatGPT 401 that says the token sent has expired and asks for a refresh (`provider.SignInExpired`, #2973) while its `exp` is ahead renews the account's sign-in once (`provider.NoteExpiredSignIn` from `noteSignIn`), keyed on the token sent, so the next request goes with a fresh one; nothing is marked, and the request fails over as any 401 does ([Providers and accounts](providers-accounts.md), A token called expired). diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 33c231648..5af4f835f 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1694,8 +1694,10 @@ func shapeRefused(status int, body []byte) bool { // supported for the API use." (Gemini, Antigravity, Code Assist; #1621), // and OpenAI's "unsupported_country_region_territory", which a relay may // pass on as a 400. It is about the address the request leaves from, not -// the request or the model: another member, going another way, may -// answer, and this one rests only as briefly as any other failure does. +// the request, the model or the account: another member, going another +// way, may answer, and none rests for it (restAfterMarked, #5182). Google +// decides it per connection, so the connection it came on is not used +// again (regionFresh). // A request's own field named location ("location field is not // supported") isn't one. var regionWords = regexp.MustCompile(`(?i)\buser location is not supported for the api use\b|unsupported_country_region_territory|country, region,? or territory not supported`) @@ -2011,6 +2013,11 @@ func passing(status int, header http.Header, body []byte, again int) (time.Durat // 后再试"); a plan used up or no money left won't clear in seconds, // nor an account's token wall (walled) return wait, again < rateRetries && failure(status, body) == failRate && !creditWords.Match(wordsOf(body)) && !walled(body) + case regionRefused(status, wordsOf(body)): + // refused at the edge the connection reached, which a new + // connection a moment later may not be (#5182: answered 12s on); + // the try goes out on a new one (regionFresh) + return wait, again < lastRetries } return 0, false } diff --git a/internal/gateway/region_fallback_test.go b/internal/gateway/region_fallback_test.go index 110fae051..a59f905d1 100644 --- a/internal/gateway/region_fallback_test.go +++ b/internal/gateway/region_fallback_test.go @@ -55,8 +55,8 @@ func TestRegionRefusalIsNotTooLong(t *testing.T) { } // #1621: a group's member refused for its region hands the request to the -// next member, and rests as briefly as any failure, not as one out of -// credit or quota. +// next member, and rests not at all (#5182): not as one out of credit or +// quota, nor as any failure. func TestGroupFailsOverARegionRefusal(t *testing.T) { for _, body := range []string{antigravityRegion400, googleRegion400} { fresh(t) @@ -76,7 +76,7 @@ func TestGroupFailsOverARegionRefusal(t *testing.T) { if len(r.Tries) != 2 || r.Tries[0].Status != 400 || r.Tries[0].Rest == nil { t.Fatalf("tries %+v", r.Tries) } - if rest := r.Tries[0].Rest; rest.Why != failOther || time.Until(rest.Until) > longestRetry { + if rest := r.Tries[0].Rest; rest.Why != failOther || rest.By != "off" || rest.Failures != 0 || time.Until(rest.Until) > 0 { t.Fatalf("rested %+v", rest) } } diff --git a/internal/gateway/region_fresh_test.go b/internal/gateway/region_fresh_test.go new file mode 100644 index 000000000..2e7ce6487 --- /dev/null +++ b/internal/gateway/region_fresh_test.go @@ -0,0 +1,264 @@ +package gateway + +import ( + "context" + "crypto/tls" + "crypto/x509" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// edgeVendor is #5182's Google edge: the connection the first request +// came on is refused for where it comes from, every request on it after +// too, whatever account it carries, while a request on any other +// connection is answered. conns lists each request's connection, in the +// order they came. +type edgeVendor struct { + srv *httptest.Server + mu sync.Mutex + bad string + conns []string + who []string + // refuse is the refusal the bad connection answers + refuse string +} + +func newEdgeVendor(t *testing.T, h2 bool, refuse string) *edgeVendor { + v := &edgeVendor{refuse: refuse} + v.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + switch { + case strings.Contains(r.URL.Path, ":loadCodeAssist"): + io.WriteString(w, `{"currentTier":{"id":"standard-tier"},"cloudaicompanionProject":"p1"}`) + return + case strings.Contains(r.URL.Path, ":fetchAvailableModels"): + io.WriteString(w, `{"models":{"m":{}}}`) + return + } + who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + v.mu.Lock() + if v.bad == "" { + v.bad = r.RemoteAddr + } + v.conns = append(v.conns, r.RemoteAddr) + v.who = append(v.who, who) + bad := r.RemoteAddr == v.bad + v.mu.Unlock() + if bad { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, v.refuse) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"from `+who+`"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":3}}}`)) + })) + v.srv.EnableHTTP2 = h2 + v.srv.StartTLS() + t.Cleanup(v.srv.Close) + return v +} + +func (v *edgeVendor) asked() (conns, who []string) { + v.mu.Lock() + defer v.mu.Unlock() + return append([]string(nil), v.conns...), append([]string(nil), v.who...) +} + +// trustVendor has the gateway's transports, made after it, trust v's +// certificate. +func trustVendor(t *testing.T, v *httptest.Server) { + pool := x509.NewCertPool() + pool.AddCert(v.Certificate()) + was := upstreamTLS + upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"} + t.Cleanup(func() { upstreamTLS = was }) +} + +// #5182: the gateway's own transport (upstreamTransport) doesn't send a +// request on the connection a vendor refused one on for where it comes +// from; a refusal of another kind keeps its connection, as any reply's. +// Over HTTP/2, as Google's front speaks, and HTTP/1.1. +func TestRegionRefusalDropsItsConnection(t *testing.T) { + for _, h2 := range []bool{true, false} { + for _, tc := range []struct { + name, refuse string + fresh bool + }{ + {"region", googleRegion400, true}, + {"other 400", `{"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}}`, false}, + } { + t.Run(fmt.Sprintf("h2=%v/%s", h2, tc.name), func(t *testing.T) { + fresh(t) + v := newEdgeVendor(t, h2, tc.refuse) + trustVendor(t, v.srv) + s := New() + u := "https://" + v.srv.Listener.Addr().String() + "/v1internal:streamGenerateContent" + ask := func() (int, string) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, strings.NewReader(`{}`)) + req.Header.Set("Authorization", "Bearer u@example.com") + res, err := s.client.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + if h2 && res.ProtoMajor != 2 || !h2 && res.ProtoMajor != 1 { + t.Fatalf("spoken %s", res.Proto) + } + return res.StatusCode, string(b) + } + if code, body := ask(); code != 400 { + t.Fatalf("first request: %d %s", code, body) + } + code, body := ask() + conns, _ := v.asked() + if len(conns) != 2 { + t.Fatalf("asked on %v", conns) + } + if tc.fresh { + if conns[1] == conns[0] { + t.Fatalf("the request after the region refusal went on the refused connection %s: %d %s", conns[0], code, body) + } + if code != 200 { + t.Fatalf("the new connection: %d %s", code, body) + } + } else if conns[1] != conns[0] { + t.Fatalf("a plain 400 dropped its connection: %v", conns) + } + }) + } + } +} + +// antigravityOnEdge is antigravityGroupFor's Antigravity accounts, their +// upstream v reached through the gateway's region watch (regionFresh) over +// a transport that dials v for Google's hosts. +func antigravityOnEdge(t *testing.T, users []string, v *edgeVendor) *Server { + s, _ := antigravityGroupFor(t, users, "m", func(w http.ResponseWriter, r *http.Request) { + t.Errorf("asked through the fake transport: %s", r.URL) + }) + pool := x509.NewCertPool() + pool.AddCert(v.srv.Certificate()) + addr := v.srv.Listener.Addr().String() + tr := &http.Transport{ + ForceAttemptHTTP2: true, + TLSClientConfig: &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"}, + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, network, addr) + }, + } + t.Cleanup(tr.CloseIdleConnections) + s.client = &http.Client{Transport: rpmTransport{freshAfterRegion(tr)}} + return s +} + +// #5182 (ggdayup): Antigravity refused a request for where it came from, +// and every account after it was sent the same request on the same +// kept-alive connection, refused the same, and rested, the agent told a +// 400, while a new connection was answered. The next account now goes out +// on a new connection and answers, and the account refused rests not. +func TestAntigravityRegionRefusalAsksTheNextOnANewConnection(t *testing.T) { + v := newEdgeVendor(t, true, googleRegion400) + s := antigravityOnEdge(t, []string{"u1@example.com", "u2@example.com"}, v) + code, out := turnOn(t, s, directTurn("You are a helpful assistant.", false)) + conns, who := v.asked() + if code != 200 || !strings.Contains(out, "from u") { + t.Fatalf("the turn: %d %s (asked %v on %v)", code, out, who, conns) + } + if len(conns) != 2 || conns[0] == conns[1] { + t.Fatalf("asked %v on %v; want the second on a new connection", who, conns) + } + if who[0] == who[1] { + t.Fatalf("the refused account was asked first again: %v", who) + } + if !strings.Contains(out, "from "+who[1]) { + t.Fatalf("answered by someone else than %s: %s", who[1], out) + } + for _, u := range []string{"u1@example.com", "u2@example.com"} { + if r, ok := restOf("antigravity@" + u); ok { + t.Fatalf("%s rests for a refusal of where the request came from: %+v", u, r) + } + } + r := lastRoute(s) + if len(r.Tries) != 2 || r.Tries[0].Status != 400 || r.Tries[0].Rest == nil || r.Tries[0].Rest.By != "off" { + t.Fatalf("tries %+v", r.Tries) + } +} + +// #5182: the only account, refused for where the request came from, is +// asked again a moment later, on a new connection, and answers. +func TestAntigravityRegionRefusalAsksTheLastAgain(t *testing.T) { + pause := retryPause + retryPause = time.Millisecond + t.Cleanup(func() { retryPause = pause }) + v := newEdgeVendor(t, true, googleRegion400) + s := antigravityOnEdge(t, []string{"u@example.com"}, v) + code, out := turnOn(t, s, directTurn("You are a helpful assistant.", false)) + conns, who := v.asked() + if code != 200 || !strings.Contains(out, "from u@example.com") { + t.Fatalf("the turn: %d %s (asked %v on %v)", code, out, who, conns) + } + if len(conns) != 2 || conns[0] == conns[1] { + t.Fatalf("asked on %v; want the second on a new connection", conns) + } + if r, ok := restOf("antigravity@u@example.com"); ok { + t.Fatalf("the account rests: %+v", r) + } +} + +// #5182: a region refusal rests no account, every route's rest alike +// (restAfter), and counts no failure: the account is asked first again. +// A 500 on the same account still rests it as before. +func TestRegionRefusalRestsNoAccount(t *testing.T) { + for _, body := range []string{googleRegion400, antigravityRegion400} { + s, askedUsage := antigravityTurnedAwayGroup(t, []string{"u1@example.com", "u2@example.com"}, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, body) + }) + for turn := range 2 { + code, out := turnOn(t, s, claudeTurn("You are a helpful assistant.")) + if code != 200 || !strings.Contains(out, "from the other") { + t.Fatalf("turn %d: %d %s", turn, code, out) + } + r := lastRoute(s) + if len(r.Tries) != 3 || !strings.HasPrefix(r.Tries[0].ID, "antigravity") || !strings.HasPrefix(r.Tries[1].ID, "antigravity") || r.Tries[0].ID == r.Tries[1].ID || r.Tries[2].ID != "other" { + t.Fatalf("turn %d asked %+v; want both accounts, then the other", turn, r.Tries) + } + for _, try := range r.Tries[:2] { + if try.Rest == nil || try.Rest.By != "off" || try.Rest.Failures != 0 { + t.Fatalf("turn %d: a try rested %+v", turn, try.Rest) + } + } + } + for _, u := range []string{"u1@example.com", "u2@example.com"} { + if r, ok := restOf("antigravity@" + u); ok { + t.Fatalf("%s rests for %s: %+v (%v)", u, body, r, rests()) + } + } + if *askedUsage != 0 { + t.Fatalf("usage asked again %d times", *askedUsage) + } + } + // the boundary: Google's own failure still rests the account + s, _ := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + io.WriteString(w, `{"error":{"code":500,"message":"Internal error encountered.","status":"INTERNAL"}}`) + }) + turnOn(t, s, claudeTurn("You are a helpful assistant.")) + if _, ok := restOf("antigravity@u@example.com"); !ok { + t.Fatalf("a 500 no longer rests the account: %+v", lastRoute(s).Tries) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index e45423ea6..ac03a663a 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1318,6 +1318,16 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // was, and is asked again once the network is back (offline.go) return Rest{Why: failOffline, Status: status, By: "off", Until: now} } + if regionRefused(status, wordsOf(body)) { + // the vendor refused where the request came from (regionWords): + // the network's doing, and the edge's the connection reached, not + // the account's. Every account asked on that connection was + // refused the same, and all of them rested, while a new + // connection answered seconds later (#5182). None is set aside + // and the failure counts nowhere; the next try goes out on a new + // connection (regionFresh) + return Rest{Why: why, Status: status, By: "off", Until: now} + } if status == http.StatusBadGateway && bytes.Contains(body, []byte(openCodeBare)) { // OpenCode's bare 400 (openCodeBareRefusal, #3740) is about the // request, not the key: the key's other requests go through, so diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go index 343fe1692..4a2c2e9c2 100644 --- a/internal/gateway/upstream_transport.go +++ b/internal/gateway/upstream_transport.go @@ -4,10 +4,12 @@ import ( "crypto/tls" "errors" "fmt" + "io" "net" "net/http" "net/http/httptrace" "strings" + "sync" "sync/atomic" "time" @@ -25,7 +27,8 @@ var upstreamTLS *tls.Config // other vendor is spoken HTTP/2 to wherever it offers it. A large body // whose connection was dropped for a lost ping goes again through a // transport that does not ping (#3909), and so do the large bodies after -// it for a while (slowFor). A request that +// it for a while (slowFor). A connection a vendor refused a request on +// for where it comes from is not used again (regionFresh). A request that // finds its kept-alive connection dropped is sent again on a new one // (replayable). A vendor is given upstreamHeaderWait to begin answering, // but for a drawing, which an images API answers only once it has drawn: @@ -33,9 +36,9 @@ var upstreamTLS *tls.Config // Image generation timeout gives it (drawWithin), up to 60 minutes. func upstreamTransport() http.RoundTripper { return drawsApart{ - any: codexSocket{replayable{netproxy.Dispatch(vendorTransport(upstreamHeaderWait))}}, - draws: replayable{netproxy.Dispatch(vendorTransport(0))}, - uploads: codexSocket{replayable{netproxy.Dispatch(uploadTransport(upstreamHeaderWait))}}, + any: codexSocket{replayable{freshAfterRegion(netproxy.Dispatch(vendorTransport(upstreamHeaderWait)))}}, + draws: replayable{freshAfterRegion(netproxy.Dispatch(vendorTransport(0)))}, + uploads: codexSocket{replayable{freshAfterRegion(netproxy.Dispatch(uploadTransport(upstreamHeaderWait)))}}, slow: new(atomic.Int64), } } @@ -249,3 +252,88 @@ func (e errClosedUnsent) Unwrap() error { return e.err } // closedUnsentWords mark errClosedUnsent in a failure's message. const closedUnsentWords = "closed before sent" + +// regionFresh drops the kept-alive connections of next once a vendor has +// refused a request on one of them for where it comes from (regionWords): +// Google's 400 "User location is not supported for the API use." is +// decided per connection by the edge it reached, and the next request on +// that connection, whatever account it carries, was refused the same, +// while a new connection, to another edge, was answered (#5182, ggdayup: +// every Antigravity account of a pool refused within 10s on one reused +// connection, a new one answered 12s later). The refused reply's body is +// watched as it is read; when it ends, the idle connections are closed, +// so the try after it dials a new one. A connection another request is +// still reading at that moment is left to finish, and dropped before the +// next request through next instead (pending), if it is idle by then. +type regionFresh struct { + next http.RoundTripper + pending *atomic.Bool +} + +func freshAfterRegion(next http.RoundTripper) regionFresh { + return regionFresh{next: next, pending: new(atomic.Bool)} +} + +func (t regionFresh) RoundTrip(r *http.Request) (*http.Response, error) { + if t.pending.CompareAndSwap(true, false) { + t.CloseIdleConnections() + } + res, err := t.next.RoundTrip(r) + if err != nil || res.StatusCode < 400 || res.Body == nil || res.Body == http.NoBody { + return res, err + } + res.Body = ®ionWatch{ReadCloser: res.Body, t: t} + return res, nil +} + +// CloseIdleConnections closes next's, where it keeps any. +func (t regionFresh) CloseIdleConnections() { + if c, ok := t.next.(interface{ CloseIdleConnections() }); ok { + c.CloseIdleConnections() + } +} + +// regionWatchBytes is how much of a failed reply's body regionWatch keeps +// to read the refusal's words from: an error's words come first. +const regionWatchBytes = 8 << 10 + +// regionWatch is a failed reply's body, its first bytes kept: once it is +// read to its end or closed, a region refusal in them has the +// connections dropped (regionFresh). +type regionWatch struct { + io.ReadCloser + t regionFresh + mu sync.Mutex + head []byte + done bool +} + +func (b *regionWatch) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + b.mu.Lock() + defer b.mu.Unlock() + if room := regionWatchBytes - len(b.head); room > 0 && n > 0 { + b.head = append(b.head, p[:min(n, room)]...) + } + if err == io.EOF && !b.done && regionWords.Match(wordsOf(b.head)) { + // HTTP/1.1 puts the connection back as the body ends, before any + // Close: the next request through the transport finds it gone + b.t.pending.Store(true) + } + return n, err +} + +func (b *regionWatch) Close() error { + err := b.ReadCloser.Close() + b.mu.Lock() + refused := !b.done && regionWords.Match(wordsOf(b.head)) + b.done = true + b.mu.Unlock() + if refused { + // the stream is over once Close returns: its connection is idle, + // unless another request is on it + b.t.pending.Store(true) + b.t.CloseIdleConnections() + } + return err +}