From 1f8d01286b6913bd9233d7eb25cfb00382e5388a Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 18:27:47 +0100 Subject: [PATCH 01/10] fix(gateway): escape a session-scoped free-tier 429 by re-minting the session The free tier ledges free-model usage per session id, not per egress: once a conversation spends its allowance every relay answers 429 "Free usage limit reached" for that session, so exit rotation cannot recover it, and a fork of the conversation keeps the same derived id and stays burned. Re-mint the session once on that exact 429 and retry the routing pass. Only sessions the gateway minted itself are re-minted, so official client session ids keep their affinity, and the replacement is deterministic (bootNonce-salted, memoized) so the rest of the conversation reuses it instead of re-paying the exit walk. A session-scoped 429 no longer cools the exit: the burn is not the relay's fault and cooling it could leave the retry with no exit left. --- internal/gateway/session_escape.go | 155 ++++++++++++++++++++++++ internal/gateway/session_escape_test.go | 90 ++++++++++++++ internal/gateway/upstream.go | 30 ++++- internal/identity/request.go | 39 +++++- internal/identity/request_test.go | 69 +++++++++++ 5 files changed, 375 insertions(+), 8 deletions(-) create mode 100644 internal/gateway/session_escape.go create mode 100644 internal/gateway/session_escape_test.go create mode 100644 internal/identity/request_test.go diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go new file mode 100644 index 00000000..00ca70e7 --- /dev/null +++ b/internal/gateway/session_escape.go @@ -0,0 +1,155 @@ +package gateway + +import ( + "bytes" + "context" + "io" + "net/http" + "sync" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "opencode2api/internal/identity" + "opencode2api/internal/models" + "opencode2api/internal/telemetry" +) + +// freeUsageLimitMarkers are the error bodies the free tier returns when a +// session or egress has spent its free-model allowance. The type name is stable +// across the wordings observed so far; the message is the human form. +var freeUsageLimitMarkers = []string{"freeusagelimiterror", "free usage limit"} + +// isFreeUsageLimitResponse reports whether resp is the free tier's free-model +// allowance rejection. The body is peeked and restored, so the caller can still +// forward the response. +func isFreeUsageLimitResponse(resp *http.Response) bool { + if resp == nil || resp.StatusCode != http.StatusTooManyRequests { + return false + } + body := peekResponseBody(resp) + if len(body) == 0 { + return false + } + lower := bytes.ToLower(body) + for _, marker := range freeUsageLimitMarkers { + if bytes.Contains(lower, []byte(marker)) { + return true + } + } + return false +} + +// sessionScopedFreeLimit reports whether the attempt's free-tier allowance +// rejection can belong to the session rather than to the exit. The gateway +// re-mints a session it minted itself and retries once, so such a response must +// not cool the exit: a healthy relay would be parked and the retry could find +// no exit left, which would make the escape impossible on a small pool. +func sessionScopedFreeLimit(ids identity.RequestIDs, resp *http.Response, err error) bool { + return err == nil && ids.SessionDerived && isFreeUsageLimitResponse(resp) +} + +// sessionEscapeLimit bounds the memo of burned-session replacements so callers +// that keep opening fresh conversations cannot grow it without bound. +const sessionEscapeLimit = 4096 + +type sessionEscapeKey struct{ session, child, parent string } + +type sessionEscapeValue struct{ session, child, parent string } + +var sessionEscapes = struct { + sync.Mutex + entries map[sessionEscapeKey]sessionEscapeValue +}{entries: map[sessionEscapeKey]sessionEscapeValue{}} + +func sessionEscapeKeyOf(ids identity.RequestIDs) sessionEscapeKey { + return sessionEscapeKey{ids.Session, ids.ChildSession, ids.ParentSession} +} + +// escapedSession returns ids with every remembered replacement applied. One +// conversation can burn more than one session over its life, so the chain is +// followed until it ends. The second result reports whether anything changed. +func escapedSession(ids identity.RequestIDs) (identity.RequestIDs, bool) { + changed := false + for range 4 { + sessionEscapes.Lock() + value, ok := sessionEscapes.entries[sessionEscapeKeyOf(ids)] + sessionEscapes.Unlock() + if !ok { + break + } + ids.Session, ids.ChildSession, ids.ParentSession = value.session, value.child, value.parent + changed = true + } + return ids, changed +} + +// rememberSessionEscape records that the free tier rejected original's session +// and that escaped works. Once the memo is full it is dropped whole, which only +// costs the oldest conversations one fresh escape. +func rememberSessionEscape(original, escaped identity.RequestIDs) { + key := sessionEscapeKeyOf(original) + sessionEscapes.Lock() + defer sessionEscapes.Unlock() + if _, exists := sessionEscapes.entries[key]; !exists && len(sessionEscapes.entries) >= sessionEscapeLimit { + sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeValue{} + } + sessionEscapes.entries[key] = sessionEscapeValue{escaped.Session, escaped.ChildSession, escaped.ParentSession} +} + +// escapeBurnedSession retries one routing pass with a re-minted session when +// the last response is the free tier's usage rejection and the session was one +// the gateway minted itself. The burn follows the session id, not the egress: +// every exit answers the same 429, so rotating exits cannot help, while a fresh +// session id is a fresh bucket. Re-minting is skipped for diagnostics (a probe +// measures the request it was given) and for title requests (answered +// locally). The retry's attempt count is added to the total so telemetry keeps +// numbering one request's attempts in sequence. +func (g *Gateway) escapeBurnedSession(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, resp *http.Response, effectiveRoute models.Route, attempts int) (*http.Response, models.Route, int, error) { + if !ids.SessionDerived || isDiagnosticRequest(ctx) || ctx.Err() != nil { + return resp, effectiveRoute, attempts, nil + } + if !isFreeUsageLimitResponse(resp) { + return resp, effectiveRoute, attempts, nil + } + if isTitleGenerationBody(bodies[config.TierZen]) || isTitleGenerationBody(bodies[route.Tier]) { + return resp, effectiveRoute, attempts, nil + } + original := *resp + originalBody, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + httpx.DrainAndClose(resp.Body) + escaped := ids.WithFreshSession() + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Session = escaped.Session + } + g.logger.Info("free tier burned this session; retrying once with a fresh session", + "component", "upstream", "event", "free_limit_session_retry", "request_id", ids.Request, + "model", route.ID, "session", ids.Session, "fresh_session", escaped.Session, + "retry_after", resp.Header.Get("Retry-After")) + retryResp, retryRoute, used, retryErr := g.doUpstreamTiers(ctx, route, bodies, escaped, attempts) + attempts += used + if retryErr == nil && retryResp != nil && retryResp.StatusCode/100 == 2 { + rememberSessionEscape(ids, escaped) + return retryResp, retryRoute, attempts, nil + } + if retryErr != nil && ctx.Err() != nil { + if retryResp != nil { + httpx.DrainAndClose(retryResp.Body) + } + return nil, effectiveRoute, attempts, retryErr + } + if retryResp == nil || retryErr != nil { + // The retry produced no usable response and the original body was + // consumed to free its connection. Hand the client the real upstream + // cause instead of a gateway error. + if retryResp != nil { + httpx.DrainAndClose(retryResp.Body) + } + if readErr == nil { + original.Body = io.NopCloser(bytes.NewReader(originalBody)) + } else { + original.Body = http.NoBody + } + return &original, effectiveRoute, attempts, nil + } + return retryResp, retryRoute, attempts, retryErr +} diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go new file mode 100644 index 00000000..22476bcf --- /dev/null +++ b/internal/gateway/session_escape_test.go @@ -0,0 +1,90 @@ +package gateway + +import ( + "io" + "net/http" + "strconv" + "strings" + "testing" + + "opencode2api/internal/identity" +) + +func resetSessionEscapes() { + sessionEscapes.Lock() + defer sessionEscapes.Unlock() + sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeValue{} +} + +func TestIsFreeUsageLimitResponse(t *testing.T) { + const freeLimitBody = `{"error":{"code":null,"message":"Free usage limit reached. Free models work in OpenCode","param":null,"type":"upstream_error"}}` + resp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Body: io.NopCloser(strings.NewReader(freeLimitBody)), + } + if !isFreeUsageLimitResponse(resp) { + t.Fatal("expected the free usage limit body to be recognized") + } + rest, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("reading restored body: %v", err) + } + if string(rest) != freeLimitBody { + t.Fatalf("body was not restored: got %q", rest) + } + + rateLimit := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limit"}}`)), + } + if isFreeUsageLimitResponse(rateLimit) { + t.Fatal("a generic rate limit must not be recognized as the free usage limit") + } + + ok := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(freeLimitBody)), + } + if isFreeUsageLimitResponse(ok) { + t.Fatal("a 200 must not be recognized as the free usage limit") + } + + if isFreeUsageLimitResponse(nil) { + t.Fatal("a nil response must not be recognized as the free usage limit") + } +} + +func TestSessionEscapeMemoChains(t *testing.T) { + resetSessionEscapes() + first := identity.RequestIDs{Session: "ses_first"} + second := first.WithFreshSession() + third := second.WithFreshSession() + rememberSessionEscape(first, second) + rememberSessionEscape(second, third) + + got, ok := escapedSession(first) + if !ok { + t.Fatal("expected the first session to have a remembered replacement") + } + if got.Session != third.Session { + t.Fatalf("chain did not reach the last replacement: got %q want %q", got.Session, third.Session) + } + + unknown := identity.RequestIDs{Session: "ses_unknown"} + if _, ok := escapedSession(unknown); ok { + t.Fatal("an unknown session must not report a replacement") + } +} + +func TestSessionEscapeMemoCaps(t *testing.T) { + resetSessionEscapes() + for i := 0; i < sessionEscapeLimit+8; i++ { + original := identity.RequestIDs{Session: "ses_" + strconv.Itoa(i)} + rememberSessionEscape(original, original.WithFreshSession()) + } + sessionEscapes.Lock() + defer sessionEscapes.Unlock() + if len(sessionEscapes.entries) > sessionEscapeLimit { + t.Fatalf("memo grew past its limit: %d > %d", len(sessionEscapes.entries), sessionEscapeLimit) + } +} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index be470980..7ec75f9b 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -154,11 +154,32 @@ func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) { // buffered (up to 1 MiB) so it can be read again. Debug key overrides skip the // replay so the Playground sees the selected key's own answer. func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs) (*http.Response, models.Route, error) { + if !isDiagnosticRequest(ctx) { + // A conversation whose session the free tier already burned is sent with + // its remembered replacement, so the request starts on the fresh bucket + // instead of spending a full exit walk rediscovering the 429. + if escaped, ok := escapedSession(ids); ok { + ids = escaped + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Session = ids.Session + } + g.logger.Debug("using a remembered replacement session", "component", "upstream", "event", "free_limit_session_memo", "request_id", ids.Request, "session", ids.Session) + } + } resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) if _, selected := debugKeyOverrideFrom(ctx); selected { return resp, effectiveRoute, err } - if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest { + if err != nil || resp == nil { + return resp, effectiveRoute, err + } + if resp.StatusCode == http.StatusTooManyRequests { + resp, effectiveRoute, attempts, err = g.escapeBurnedSession(ctx, route, bodies, ids, resp, effectiveRoute, attempts) + if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest { + return resp, effectiveRoute, err + } + } + if resp.StatusCode != http.StatusBadRequest { return resp, effectiveRoute, err } origBody := resp.Body @@ -606,7 +627,12 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b if ctx.Err() != nil { break } - g.observeAnonymousResult(ctx, node, nodeResp, nodeErr) + if !sessionScopedFreeLimit(ids, nodeResp, nodeErr) { + // A burned session is not this exit's fault: the escape retry below + // re-mints the session, so cooling the exit would park a healthy + // relay and could leave that retry with nothing to use. + g.observeAnonymousResult(ctx, node, nodeResp, nodeErr) + } if g.anonymous.Open() { // This attempt tripped the breaker (or another request did): // continuing the walk would keep probing a lane that is now diff --git a/internal/identity/request.go b/internal/identity/request.go index 2f421e4d..f74bf451 100644 --- a/internal/identity/request.go +++ b/internal/identity/request.go @@ -38,6 +38,12 @@ type RequestIDs struct { Message string Project string ParentSession string + // SessionDerived reports that the gateway minted Session itself, from a + // conversation seed or a re-encoded client id, rather than preserving an + // official OpenCode session verbatim. Only a derived session may be + // re-minted to escape an upstream quota bucket: no client state depends on + // its value. + SessionDerived bool } // DeriveRequestIDs derives the upstream identity of one request. scope names @@ -72,6 +78,7 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques if signal == "" || signal == `{}` { signal = RandomID("fallback", 16) } + sessionDerived := !isOfficialSessionID(signal) session := scopedSessionID(scope, signal) childSession := r.Header.Get("x-opencode-session-id") if childSession != "" { @@ -93,12 +100,13 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques parentSession = scopedSessionID(scope, parentSession) } return RequestIDs{ - Session: session, - ChildSession: childSession, - Request: RandomID("req", 16), - Message: UserMessageID(r, body, session), - Project: projectSignal, - ParentSession: parentSession, + Session: session, + ChildSession: childSession, + Request: RandomID("req", 16), + Message: UserMessageID(r, body, session), + Project: projectSignal, + ParentSession: parentSession, + SessionDerived: sessionDerived, } } @@ -114,6 +122,25 @@ func scopedSessionID(scope, signal string) string { return CanonicalSessionID(signal) } +// WithFreshSession returns ids whose upstream sessions are re-minted from the +// current ones. The free tier ledges free-model usage per session id, so a +// session that exhausted its bucket is answered with 429 "Free usage limit +// reached" on every egress, however often the exit rotates; a re-minted session +// is a fresh bucket. The derivation is deterministic and salted with bootNonce, +// so one conversation keeps one replacement identity for the life of the +// process instead of losing its prompt cache on every request. Request and +// Message are preserved: they identify the request, not the conversation. +func (ids RequestIDs) WithFreshSession() RequestIDs { + ids.Session = CanonicalSessionID("remint\x00" + ids.Session) + if ids.ChildSession != "" { + ids.ChildSession = CanonicalSessionID("remint\x00" + ids.ChildSession) + } + if ids.ParentSession != "" { + ids.ParentSession = CanonicalSessionID("remint\x00" + ids.ParentSession) + } + return ids +} + // claudeCodeSessionPattern extracts the per-session UUID Claude Code embeds in // metadata.user_id ("user__account__session_"). var claudeCodeSessionPattern = regexp.MustCompile(`_session_([0-9A-Fa-f-]{36})$`) diff --git a/internal/identity/request_test.go b/internal/identity/request_test.go new file mode 100644 index 00000000..0b28b03a --- /dev/null +++ b/internal/identity/request_test.go @@ -0,0 +1,69 @@ +package identity + +import ( + "net/http/httptest" + "strings" + "testing" +) + +func TestDeriveRequestIDsMarksSynthesizedSessions(t *testing.T) { + body := map[string]any{"system": "sys", "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader("{}")) + ids := DeriveRequestIDs(r, body, "scope") + if !ids.SessionDerived { + t.Fatal("expected a conversation-derived session to be marked derived") + } + if !canonicalSessionPattern.MatchString(ids.Session) { + t.Fatalf("session %q does not match the canonical pattern", ids.Session) + } + if !descendingTimePartPattern.MatchString(ids.Session[4:16]) { + t.Fatalf("session %q time part %q does not match the descending pattern", ids.Session, ids.Session[4:16]) + } + + const official = "ses_e9c3455c3ffe47zLLfuYyviLPd" + r.Header.Set("x-opencode-session", official) + ids2 := DeriveRequestIDs(r, body, "scope") + if ids2.SessionDerived { + t.Fatal("expected an official client session not to be marked derived") + } + if ids2.Session != official { + t.Fatalf("official session changed: got %q want %q", ids2.Session, official) + } +} + +func TestWithFreshSessionIsStableAndDistinct(t *testing.T) { + body := map[string]any{"system": "sys", "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader("{}")) + ids := DeriveRequestIDs(r, body, "scope") + escaped := ids.WithFreshSession() + if escaped.Session == ids.Session { + t.Fatal("re-minted session equals the original") + } + if !canonicalSessionPattern.MatchString(escaped.Session) { + t.Fatalf("re-minted session %q does not match the canonical pattern", escaped.Session) + } + if escaped.Request != ids.Request || escaped.Message != ids.Message { + t.Fatal("re-minting changed the request or message identity") + } + if ids.WithFreshSession().Session != escaped.Session { + t.Fatal("re-minting is not deterministic") + } + if escaped.WithFreshSession().Session == escaped.Session { + t.Fatal("re-minting an already re-minted session did not advance") + } + + r2 := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader("{}")) + r2.Header.Set("x-opencode-session-id", "client-child") + r2.Header.Set("x-parent-session-id", "client-parent") + ids2 := DeriveRequestIDs(r2, body, "scope") + escaped2 := ids2.WithFreshSession() + if ids2.ChildSession == "" || ids2.ParentSession == "" { + t.Fatalf("expected child and parent sessions, got %q and %q", ids2.ChildSession, ids2.ParentSession) + } + if escaped2.ChildSession == ids2.ChildSession { + t.Fatal("child session was not re-minted") + } + if escaped2.ParentSession == ids2.ParentSession { + t.Fatal("parent session was not re-minted") + } +} From 1e01ebfe97d426cc076e63acadd76c0114251130 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 18:37:54 +0100 Subject: [PATCH 02/10] fix(gateway): stop the anonymous walk on the first session-scoped free-limit 429 A free-limit 429 follows the session id, not the exit, so every relay and base URL answers it identically. The walk previously spent the whole exit set on guaranteed 429s before doUpstream re-minted the session; a burned conversation cost 9 relays and ~15s on its first request. Break the walk on the first such 429 so the escape costs one rejected attempt plus the retry. --- internal/gateway/upstream.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 7ec75f9b..4b16dccd 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -477,6 +477,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b // then reports errDeterministicClientRejection so the caller keeps this // 4xx instead of replacing it with a later tier's answer. halted := false + // burned records that the free tier rejected this session's allowance. + // The burn follows the session id, not the exit, so the walk stops after + // the first such 429 and doUpstream re-mints the session and retries once. + burned := false cursor := g.anonymous.CursorForOffset(ids.Session, attemptOffset) limit := min(g.anonymous.Len(), g.maxAnonymousExits()) if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit { @@ -609,6 +613,14 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b halted = true g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) break + } else if sessionScopedFreeLimit(ids, resp, err) { + // The burn follows the session, not the exit: every relay and + // base URL answers this session with the same free-limit 429. + // Stop the walk now so doUpstream re-mints the session and + // retries once instead of spending every exit on a guaranteed + // 429. + burned = true + break } else { g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) } @@ -616,6 +628,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b break } } + if burned { + break + } if halted { // A request-level rejection is identical on every exit: another // proxy cannot shorten the context or repair the payload. Keep the From 5039ba10ae05d7c7317abed245ebc6e1982391bd Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 18:43:31 +0100 Subject: [PATCH 03/10] fix(gateway): let the re-minted retry walk exits like a normal request The early break on a session-scoped free-limit 429 must apply only to the original routing pass. On the re-minted retry the answer can still be exit-specific (a relay or its egress may reject the fresh session too), so breaking there left the retry with a single exit and turned recoverable requests into 429s. Mark the retry pass and keep the break for the burned original only. --- internal/gateway/session_escape.go | 17 ++++++++++++++++- internal/gateway/upstream.go | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index 00ca70e7..2b953687 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -39,6 +39,21 @@ func isFreeUsageLimitResponse(resp *http.Response) bool { return false } +// sessionRemintKey marks a routing pass that already uses a re-minted session. +// Such a pass must not stop at the first free-limit 429, because the answer may +// still be exit-specific: the fresh session has to walk exits like any normal +// request, while a burned original session does not. +type sessionRemintKey struct{} + +func withSessionRemint(ctx context.Context) context.Context { + return context.WithValue(ctx, sessionRemintKey{}, true) +} + +func sessionReminted(ctx context.Context) bool { + reminted, _ := ctx.Value(sessionRemintKey{}).(bool) + return reminted +} + // sessionScopedFreeLimit reports whether the attempt's free-tier allowance // rejection can belong to the session rather than to the exit. The gateway // re-mints a session it minted itself and retries once, so such a response must @@ -125,7 +140,7 @@ func (g *Gateway) escapeBurnedSession(ctx context.Context, route models.Route, b "component", "upstream", "event", "free_limit_session_retry", "request_id", ids.Request, "model", route.ID, "session", ids.Session, "fresh_session", escaped.Session, "retry_after", resp.Header.Get("Retry-After")) - retryResp, retryRoute, used, retryErr := g.doUpstreamTiers(ctx, route, bodies, escaped, attempts) + retryResp, retryRoute, used, retryErr := g.doUpstreamTiers(withSessionRemint(ctx), route, bodies, escaped, attempts) attempts += used if retryErr == nil && retryResp != nil && retryResp.StatusCode/100 == 2 { rememberSessionEscape(ids, escaped) diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 4b16dccd..036d9920 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -613,7 +613,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b halted = true g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) break - } else if sessionScopedFreeLimit(ids, resp, err) { + } else if sessionScopedFreeLimit(ids, resp, err) && !sessionReminted(ctx) { // The burn follows the session, not the exit: every relay and // base URL answers this session with the same free-limit 429. // Stop the walk now so doUpstream re-mints the session and From 3a51341f91735ea12a3a5216b1e34cfdfc2254c0 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 18:53:02 +0100 Subject: [PATCH 04/10] refactor(gateway): follow the full escape chain and test the walk-stop rule escapedSession stopped after four hops, so a conversation that burned five or more session buckets kept resolving to an already-spent id: every request paid an extra escape, and once the next bucket also burned it could not advance at all. Follow the chain to its end (bounded by the memo size) so the lookup always returns the current head. Move the anonymous walk-stop decision into stopBurnedWalk and test it, plus a long-chain test. The earlier regression shipped because that decision had no test. Collapse the duplicate memo value struct into the key type. --- internal/gateway/session_escape.go | 23 +++++++++---- internal/gateway/session_escape_test.go | 44 ++++++++++++++++++++++++- internal/gateway/upstream.go | 2 +- 3 files changed, 60 insertions(+), 9 deletions(-) diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index 2b953687..e8c5cae8 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -63,18 +63,25 @@ func sessionScopedFreeLimit(ids identity.RequestIDs, resp *http.Response, err er return err == nil && ids.SessionDerived && isFreeUsageLimitResponse(resp) } +// stopBurnedWalk reports whether the anonymous exit walk should stop on this +// response instead of trying the next exit. A free-limit rejection of the +// original session is identical on every exit, so walking cannot help; the +// re-minted retry pass keeps walking, because one particular exit may still +// reject the fresh session. +func stopBurnedWalk(ctx context.Context, ids identity.RequestIDs, resp *http.Response, err error) bool { + return !sessionReminted(ctx) && sessionScopedFreeLimit(ids, resp, err) +} + // sessionEscapeLimit bounds the memo of burned-session replacements so callers // that keep opening fresh conversations cannot grow it without bound. const sessionEscapeLimit = 4096 type sessionEscapeKey struct{ session, child, parent string } -type sessionEscapeValue struct{ session, child, parent string } - var sessionEscapes = struct { sync.Mutex - entries map[sessionEscapeKey]sessionEscapeValue -}{entries: map[sessionEscapeKey]sessionEscapeValue{}} + entries map[sessionEscapeKey]sessionEscapeKey +}{entries: map[sessionEscapeKey]sessionEscapeKey{}} func sessionEscapeKeyOf(ids identity.RequestIDs) sessionEscapeKey { return sessionEscapeKey{ids.Session, ids.ChildSession, ids.ParentSession} @@ -85,7 +92,9 @@ func sessionEscapeKeyOf(ids identity.RequestIDs) sessionEscapeKey { // followed until it ends. The second result reports whether anything changed. func escapedSession(ids identity.RequestIDs) (identity.RequestIDs, bool) { changed := false - for range 4 { + // Follow the whole chain: a long conversation burns one bucket per link, + // so stopping early would hand back a session that is already spent. + for range sessionEscapeLimit { sessionEscapes.Lock() value, ok := sessionEscapes.entries[sessionEscapeKeyOf(ids)] sessionEscapes.Unlock() @@ -106,9 +115,9 @@ func rememberSessionEscape(original, escaped identity.RequestIDs) { sessionEscapes.Lock() defer sessionEscapes.Unlock() if _, exists := sessionEscapes.entries[key]; !exists && len(sessionEscapes.entries) >= sessionEscapeLimit { - sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeValue{} + sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeKey{} } - sessionEscapes.entries[key] = sessionEscapeValue{escaped.Session, escaped.ChildSession, escaped.ParentSession} + sessionEscapes.entries[key] = sessionEscapeKeyOf(escaped) } // escapeBurnedSession retries one routing pass with a re-minted session when diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go index 22476bcf..1e6efdb6 100644 --- a/internal/gateway/session_escape_test.go +++ b/internal/gateway/session_escape_test.go @@ -1,6 +1,7 @@ package gateway import ( + "context" "io" "net/http" "strconv" @@ -13,7 +14,7 @@ import ( func resetSessionEscapes() { sessionEscapes.Lock() defer sessionEscapes.Unlock() - sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeValue{} + sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeKey{} } func TestIsFreeUsageLimitResponse(t *testing.T) { @@ -88,3 +89,44 @@ func TestSessionEscapeMemoCaps(t *testing.T) { t.Fatalf("memo grew past its limit: %d > %d", len(sessionEscapes.entries), sessionEscapeLimit) } } + +func TestSessionEscapeMemoFollowsLongChains(t *testing.T) { + resetSessionEscapes() + first := identity.RequestIDs{Session: "ses_chain"} + current := first + for i := 0; i < 8; i++ { + next := current.WithFreshSession() + rememberSessionEscape(current, next) + current = next + } + got, ok := escapedSession(first) + if !ok { + t.Fatal("expected a remembered replacement") + } + if got.Session != current.Session { + t.Fatalf("chain stopped early: got %q want %q", got.Session, current.Session) + } +} + +func TestStopBurnedWalk(t *testing.T) { + freeLimit := func() *http.Response { + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Free usage limit reached"}}`)), + } + } + derived := identity.RequestIDs{Session: "ses_x", SessionDerived: true} + if !stopBurnedWalk(context.Background(), derived, freeLimit(), nil) { + t.Fatal("a derived session's free-limit 429 must stop the original walk") + } + if stopBurnedWalk(withSessionRemint(context.Background()), derived, freeLimit(), nil) { + t.Fatal("the re-minted retry must keep walking exits") + } + official := identity.RequestIDs{Session: "ses_y"} + if stopBurnedWalk(context.Background(), official, freeLimit(), nil) { + t.Fatal("an official session must not stop the walk") + } + if stopBurnedWalk(context.Background(), derived, &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok"))}, nil) { + t.Fatal("a 200 must not stop the walk") + } +} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 036d9920..8a4ae7d1 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -613,7 +613,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b halted = true g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) break - } else if sessionScopedFreeLimit(ids, resp, err) && !sessionReminted(ctx) { + } else if stopBurnedWalk(ctx, ids, resp, err) { // The burn follows the session, not the exit: every relay and // base URL answers this session with the same free-limit 429. // Stop the walk now so doUpstream re-mints the session and From 8d6127f0f4038818b9e5534fe62e390110cbc8a1 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 19:15:50 +0100 Subject: [PATCH 05/10] gateway: park exits that spent the per-egress daily free quota The free-model allowance is per egress IP and shared by every session leaving through it, but every "Free usage limit reached" 429 was treated as session-scoped. On a partially spent pool that made the escape stop the walk, re-mint the session, and re-walk straight into exhausted exits, so the request still ended in a 429 after nine attempts. Split the two shapes by the Retry-After: a hint that lands on the next UTC midnight is the exit's daily allowance, so park that exit until the reset and keep walking instead of re-minting. A 429 without that hint stays session-scoped and keeps the existing escape. Daily-quota answers also count as neutral for the lane breaker, since the exit answered and other exits may still have quota. The cursor skips parked exits, and when the whole pool is parked it probes the soonest-reset exit once per request so the client still gets the upstream 429 rather than a gateway error. --- internal/gateway/pool.go | 77 ++++++++++++++++++++- internal/gateway/session_escape.go | 57 ++++++++++++++-- internal/gateway/session_escape_test.go | 90 +++++++++++++++++++++++-- internal/gateway/upstream.go | 23 ++++++- 4 files changed, 229 insertions(+), 18 deletions(-) diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 26dd47a7..9ac5e4c9 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -38,6 +38,7 @@ type proxyTransport struct { healthy atomic.Bool checking atomic.Bool blockedUntil atomic.Int64 + drainedUntil atomic.Int64 } // proxyTransports holds every configured proxy route, indexed by @@ -64,6 +65,25 @@ func (t *proxyTransport) markBlocked(until time.Time) { t.blockedUntil.Store(until.UnixNano()) } +// drained reports whether this exit spent the free tier's daily free-model +// allowance for its egress IP. +func (t *proxyTransport) drained(now time.Time) bool { + if t == nil { + return false + } + return t.drainedUntil.Load() > now.UnixNano() +} + +// markDrained keeps this exit out of the anonymous cursor until the free +// tier's per-IP daily allowance resets. Unlike an abuse block, this is not the +// exit's fault: the answer is a quota 429 whose Retry-After names the reset. +func (t *proxyTransport) markDrained(until time.Time) { + if t == nil { + return + } + t.drainedUntil.Store(until.UnixNano()) +} + // anonymousNodes gives the shared OpenCode "public" credential an independent // cooldown per proxy. Unlike key nodes, anonymous nodes are never rebound: // changing proxy is the failover mechanism because Zen rate-limits them by IP. @@ -105,6 +125,10 @@ type anonymousCursor struct { offset int used []bool single bool + // probedDrained records that the cursor already sent the one probe allowed + // to an exit parked on its daily allowance, so a fully drained pool answers + // with one real 429 instead of re-walking every parked exit. + probedDrained bool } // anonymousPool builds one anonymous node per proxy transport, or an empty @@ -330,9 +354,15 @@ func (c *anonymousCursor) Next() *anonymousNode { } return c.pool.nodes[index] } - now := time.Now().UnixNano() + now := time.Now() + nowNanos := now.UnixNano() + // unusable marks an exit the free tier itself told us to leave alone: an + // abuse block, or a spent daily free-model allowance parked until its reset. isBlocked := func(node *anonymousNode) bool { - return node.proxy != nil && node.proxy.blockedUntil.Load() > now + if node.proxy == nil { + return false + } + return node.proxy.blockedUntil.Load() > nowNanos || node.proxy.drained(now) } for c.offset < n { idx := (c.start + c.offset) % n @@ -345,7 +375,7 @@ func (c *anonymousCursor) Next() *anonymousNode { c.used[idx] = true continue } - if node.proxy.pool || (!c.used[idx] && node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now) { + if node.proxy.pool || (!c.used[idx] && node.proxy.healthy.Load() && node.cooldownUntil.Load() <= nowNanos) { c.used[idx] = true return node } @@ -382,9 +412,50 @@ func (c *anonymousCursor) Next() *anonymousNode { c.used[choice] = true return c.pool.nodes[choice] } + // Every exit is parked because its daily free-model allowance is spent. + // The client must still get the upstream's 429 (with its reset hint), not a + // gateway error, so probe the exit that resets soonest once per request. A + // parked exit's allowance can also recover early when the observed quota is + // shared with other traffic on that IP. + if !c.probedDrained && c.allParked(now) { + best, earliest := -1, int64(0) + for step := range n { + idx := (c.start + step) % n + node := c.pool.nodes[idx] + if node.proxy == nil || !node.proxy.drained(now) { + continue + } + until := node.proxy.drainedUntil.Load() + if best < 0 || until < earliest { + best, earliest = idx, until + } + } + if best >= 0 { + c.probedDrained = true + c.used[best] = true + return c.pool.nodes[best] + } + } return nil } +// allParked reports whether the free tier has parked every exit: each proxy is +// either under an abuse block or drained of its daily free-model allowance. +func (c *anonymousCursor) allParked(now time.Time) bool { + if c.pool == nil || len(c.pool.nodes) == 0 { + return false + } + for _, node := range c.pool.nodes { + if node.proxy == nil { + return false + } + if !node.proxy.blocked(now) && !node.proxy.drained(now) { + return false + } + } + return true +} + func (p *anonymousNodes) MarkSuccess(node *anonymousNode) { if node == nil { return diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index e8c5cae8..0eed51fa 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "sync" + "time" "opencode2api/internal/config" "opencode2api/internal/httpx" @@ -54,13 +55,55 @@ func sessionReminted(ctx context.Context) bool { return reminted } +// dailyQuotaSkew is how close a 429's Retry-After must land to the next UTC +// midnight for the rejection to be the exit's daily free-model allowance +// rather than a per-session throttle. It matches the free-quota tracker's rule. +const dailyQuotaSkew = 5 * time.Minute + +// dailyQuotaReset reports whether resp is the free tier's daily allowance +// rejection for this egress, and when that allowance resets. The free-model +// quota is per egress IP and shared by every session leaving through it: the +// body is the same "Free usage limit reached" seen for a burned session, but +// its Retry-After points at the next UTC midnight. Re-minting the session +// cannot restore an egress's allowance, so this case must park the exit +// instead of triggering the session escape. +func dailyQuotaReset(resp *http.Response, now time.Time) (time.Time, bool) { + if !isFreeUsageLimitResponse(resp) { + return time.Time{}, false + } + retry := parseRetryAfter(resp.Header.Get("Retry-After")) + // A hint under a minute is a transient throttle, not a daily reset; + // treating it as exhaustion would park a healthy exit until midnight. + if retry < time.Minute { + return time.Time{}, false + } + utc := now.UTC() + reset := time.Date(utc.Year(), utc.Month(), utc.Day()+1, 0, 0, 0, 0, time.UTC) + delta := reset.Sub(now.Add(retry)) + if delta < 0 { + delta = -delta + } + if delta > dailyQuotaSkew { + return time.Time{}, false + } + return reset, true +} + // sessionScopedFreeLimit reports whether the attempt's free-tier allowance -// rejection can belong to the session rather than to the exit. The gateway +// rejection belongs to the session rather than to the exit. The gateway // re-mints a session it minted itself and retries once, so such a response must // not cool the exit: a healthy relay would be parked and the retry could find -// no exit left, which would make the escape impossible on a small pool. -func sessionScopedFreeLimit(ids identity.RequestIDs, resp *http.Response, err error) bool { - return err == nil && ids.SessionDerived && isFreeUsageLimitResponse(resp) +// no exit left, which would make the escape impossible on a small pool. A +// daily-quota 429 is excluded: that one belongs to the egress IP and is parked +// until its reset, not answered by a new session. +func sessionScopedFreeLimit(ids identity.RequestIDs, resp *http.Response, err error, now time.Time) bool { + if err != nil || !ids.SessionDerived || !isFreeUsageLimitResponse(resp) { + return false + } + if _, daily := dailyQuotaReset(resp, now); daily { + return false + } + return true } // stopBurnedWalk reports whether the anonymous exit walk should stop on this @@ -68,8 +111,8 @@ func sessionScopedFreeLimit(ids identity.RequestIDs, resp *http.Response, err er // original session is identical on every exit, so walking cannot help; the // re-minted retry pass keeps walking, because one particular exit may still // reject the fresh session. -func stopBurnedWalk(ctx context.Context, ids identity.RequestIDs, resp *http.Response, err error) bool { - return !sessionReminted(ctx) && sessionScopedFreeLimit(ids, resp, err) +func stopBurnedWalk(ctx context.Context, ids identity.RequestIDs, resp *http.Response, err error, now time.Time) bool { + return !sessionReminted(ctx) && sessionScopedFreeLimit(ids, resp, err, now) } // sessionEscapeLimit bounds the memo of burned-session replacements so callers @@ -132,7 +175,7 @@ func (g *Gateway) escapeBurnedSession(ctx context.Context, route models.Route, b if !ids.SessionDerived || isDiagnosticRequest(ctx) || ctx.Err() != nil { return resp, effectiveRoute, attempts, nil } - if !isFreeUsageLimitResponse(resp) { + if !sessionScopedFreeLimit(ids, resp, nil, time.Now()) { return resp, effectiveRoute, attempts, nil } if isTitleGenerationBody(bodies[config.TierZen]) || isTitleGenerationBody(bodies[route.Tier]) { diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go index 1e6efdb6..139488cf 100644 --- a/internal/gateway/session_escape_test.go +++ b/internal/gateway/session_escape_test.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" "testing" + "time" "opencode2api/internal/identity" ) @@ -109,24 +110,101 @@ func TestSessionEscapeMemoFollowsLongChains(t *testing.T) { } func TestStopBurnedWalk(t *testing.T) { - freeLimit := func() *http.Response { - return &http.Response{ + now := time.Date(2026, 11, 12, 18, 0, 0, 0, time.UTC) + freeLimit := func(retryAfter string) *http.Response { + resp := &http.Response{ StatusCode: http.StatusTooManyRequests, + Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Free usage limit reached"}}`)), } + if retryAfter != "" { + resp.Header.Set("Retry-After", retryAfter) + } + return resp } derived := identity.RequestIDs{Session: "ses_x", SessionDerived: true} - if !stopBurnedWalk(context.Background(), derived, freeLimit(), nil) { + if !stopBurnedWalk(context.Background(), derived, freeLimit(""), nil, now) { t.Fatal("a derived session's free-limit 429 must stop the original walk") } - if stopBurnedWalk(withSessionRemint(context.Background()), derived, freeLimit(), nil) { + if stopBurnedWalk(withSessionRemint(context.Background()), derived, freeLimit(""), nil, now) { t.Fatal("the re-minted retry must keep walking exits") } + // The exit's own daily allowance is spent (Retry-After = next UTC midnight); + // that is not the session's burn, so the walk must continue to other exits. + if stopBurnedWalk(context.Background(), derived, freeLimit("21600"), nil, now) { + t.Fatal("a daily-quota 429 must keep walking exits") + } official := identity.RequestIDs{Session: "ses_y"} - if stopBurnedWalk(context.Background(), official, freeLimit(), nil) { + if stopBurnedWalk(context.Background(), official, freeLimit(""), nil, now) { t.Fatal("an official session must not stop the walk") } - if stopBurnedWalk(context.Background(), derived, &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok"))}, nil) { + if stopBurnedWalk(context.Background(), derived, &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok"))}, nil, now) { t.Fatal("a 200 must not stop the walk") } } + +func TestDailyQuotaReset(t *testing.T) { + now := time.Date(2026, 11, 12, 18, 0, 0, 0, time.UTC) + nextMidnight := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC) + resp := func(status int, retryAfter, body string) *http.Response { + r := &http.Response{StatusCode: status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))} + if retryAfter != "" { + r.Header.Set("Retry-After", retryAfter) + } + return r + } + const freeLimitBody = `{"error":{"type":"upstream_error","message":"Free usage limit reached. Free models work in OpenCode"}}` + + reset, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "21600", freeLimitBody), now) + if !ok { + t.Fatal("a free-limit 429 with a midnight Retry-After must be a daily-quota exhaustion") + } + if !reset.Equal(nextMidnight) { + t.Fatalf("reset = %s, want %s", reset, nextMidnight) + } + if _, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "30", freeLimitBody), now); ok { + t.Fatal("a short Retry-After must not park the exit until midnight") + } + if _, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "", freeLimitBody), now); ok { + t.Fatal("a free-limit 429 without Retry-After must stay session-scoped") + } + if _, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "21600", `{"error":{"message":"rate limit"}}`), now); ok { + t.Fatal("a non-free-limit 429 must not be treated as quota") + } +} + +func TestCursorSkipsDrainedExits(t *testing.T) { + first := &proxyTransport{index: 0, name: "a"} + second := &proxyTransport{index: 1, name: "b"} + first.healthy.Store(true) + second.healthy.Store(true) + pool := &anonymousNodes{nodes: []*anonymousNode{{proxy: first}, {proxy: second}}} + first.markDrained(time.Now().Add(time.Hour)) + cursor := &anonymousCursor{pool: pool} + if node := cursor.Next(); node == nil || node.proxy != second { + t.Fatal("a drained exit must be skipped by the anonymous cursor") + } + if node := cursor.Next(); node != nil { + t.Fatalf("the cursor must skip the drained exit every time, got %q", node.proxy.name) + } +} + +func TestCursorProbesFullyDrainedPoolOnce(t *testing.T) { + first := &proxyTransport{index: 0, name: "a"} + second := &proxyTransport{index: 1, name: "b"} + first.healthy.Store(true) + second.healthy.Store(true) + pool := &anonymousNodes{nodes: []*anonymousNode{{proxy: first}, {proxy: second}}} + reset := time.Now().Add(time.Hour) + first.markDrained(reset) + second.markDrained(reset) + cursor := &anonymousCursor{pool: pool} + // A fully drained pool must still answer with one real upstream attempt so + // the client receives the quota 429 instead of a gateway error. + if node := cursor.Next(); node == nil { + t.Fatal("a fully drained pool must probe one exit instead of returning nil") + } + if node := cursor.Next(); node != nil { + t.Fatalf("the drain probe must happen once per request, got %q", node.proxy.name) + } +} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 8a4ae7d1..78080ba3 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -613,7 +613,17 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b halted = true g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) break - } else if stopBurnedWalk(ctx, ids, resp, err) { + } else if reset, daily := dailyQuotaReset(resp, time.Now()); daily { + // The free tier's free-model allowance is per egress IP, and + // this exit has spent it: the Retry-After lands on the next UTC + // midnight. Park the exit until then and keep walking. A new + // session cannot restore an egress's allowance, so the escape + // must not fire for this shape. + if !isDiagnosticRequest(ctx) { + node.proxy.markDrained(reset) + } + g.logger.Info("free tier exhausted this exit's daily quota; parking it until reset", "component", "upstream", "event", "free_tier_daily_quota_exhausted", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "reset_at", reset.Format(time.RFC3339)) + } else if stopBurnedWalk(ctx, ids, resp, err, time.Now()) { // The burn follows the session, not the exit: every relay and // base URL answers this session with the same free-limit 429. // Stop the walk now so doUpstream re-mints the session and @@ -642,10 +652,19 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b if ctx.Err() != nil { break } - if !sessionScopedFreeLimit(ids, nodeResp, nodeErr) { + if sessionScopedFreeLimit(ids, nodeResp, nodeErr, time.Now()) { // A burned session is not this exit's fault: the escape retry below // re-mints the session, so cooling the exit would park a healthy // relay and could leave that retry with nothing to use. + } else if _, daily := dailyQuotaReset(nodeResp, time.Now()); daily { + // The exit answered but spent its own daily free-model allowance. + // That is not a lane outage: parking the exit is enough, and + // counting it as a failure would pause the whole lane while other + // exits still have quota. + if !isDiagnosticRequest(ctx) { + g.anonymous.NoteNeutral() + } + } else { g.observeAnonymousResult(ctx, node, nodeResp, nodeErr) } if g.anonymous.Open() { From 0d226da40d721c98a11f6d1d24f322a3f2867181 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 19:18:11 +0100 Subject: [PATCH 06/10] identity: correct session stability comment to UTC-day scope The re-encoded id's timestamp part is drawn from the UTC day, so the session is stable for that day; bootNonce rotates it on restart. --- internal/identity/request.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/identity/request.go b/internal/identity/request.go index f74bf451..d15a4d8b 100644 --- a/internal/identity/request.go +++ b/internal/identity/request.go @@ -251,7 +251,7 @@ func mintBootNonce() []byte { // (UUIDs, foreign client sessions, legacy gateway sessions, conversation // seeds) is re-encoded into that exact layout — inverted 48-bit millisecond // timestamp with counter 1, so the low 12 hex digits are ffe — keeping one -// stable session per conversation for the life of the process. The upstream +// stable session per conversation within a UTC day. The upstream // free tier also ties a session id to its risk/quota bookkeeping, so the // re-encoding is salted with bootNonce: a restart yields fresh ids instead of // resuming whatever the previous run's exits were charged for. A re-encoded From dcd695b938973c874e1a35edab06e8061c6fb397 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 19:44:04 +0100 Subject: [PATCH 07/10] gateway: re-mint any burned free session instead of walking exits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 20 relays are distinct tunnels that share one egress IP — verified by re-registering a WARP container, which returns the same address — so every exit answers a free-limit 429 identically and the per-exit walk only spends attempts. It also let a single dead relay turn a quota answer into a 10 s transport timeout and a gateway 504. Stop the walk on the first free-limit rejection, re-mint the session once even when the client supplied it (a burned bucket has no prompt cache left to preserve), and retry. Only when the fresh session is rejected as well does the exit get parked, which is then a real per-egress signal. Keep the earlier 429 when a later attempt only times out, so the client gets the quota answer instead of a gateway error. --- internal/gateway/pool.go | 29 +++++++++++++ internal/gateway/session_escape.go | 57 ++++++++++++++++++++----- internal/gateway/session_escape_test.go | 57 ++++++++++++++++++++++--- internal/gateway/upstream.go | 44 +++++++++---------- 4 files changed, 146 insertions(+), 41 deletions(-) diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 9ac5e4c9..53b016b4 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -39,6 +39,13 @@ type proxyTransport struct { checking atomic.Bool blockedUntil atomic.Int64 drainedUntil atomic.Int64 + + // freeLimitSession and freeLimitAt record the last session this exit + // rejected with the free-model allowance, so a rejection for another + // session within freeLimitRepeatWindow identifies a spent egress. + freeLimitMu sync.Mutex + freeLimitSession string + freeLimitAt time.Time } // proxyTransports holds every configured proxy route, indexed by @@ -55,6 +62,21 @@ func (t *proxyTransport) blocked(now time.Time) bool { return t.blockedUntil.Load() > now.UnixNano() } +// noteFreeLimit records the session this exit rejected for the free-model +// allowance and reports whether the previous rejection came from a different +// session recently, which a per-session throttle cannot explain. +func (t *proxyTransport) noteFreeLimit(session string, now time.Time) bool { + if t == nil { + return false + } + t.freeLimitMu.Lock() + defer t.freeLimitMu.Unlock() + repeat := t.freeLimitSession != "" && t.freeLimitSession != session && now.Sub(t.freeLimitAt) <= freeLimitRepeatWindow + t.freeLimitSession = session + t.freeLimitAt = now + return repeat +} + // markBlocked keeps this exit out of the anonymous cursor until until. The // block is a property of the egress IP, so it is never cleared by a response // from the same exit: only another exit can serve traffic in the meantime. @@ -402,6 +424,13 @@ func (c *anonymousCursor) Next() *anonymousNode { if isBlocked(node) { continue } + if node.cooldownUntil.Load() > nowNanos { + // A cooled exit already failed on this traffic; retrying it costs + // a full attempt timeout and turns a clean 429 into a gateway + // error when the relay blackholes. Let the caller answer with the + // last upstream response instead. + continue + } healthy := node.proxy.healthy.Load() until := node.cooldownUntil.Load() if choice < 0 || (healthy && !choiceHealthy) || (healthy == choiceHealthy && until < earliest) { diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index 0eed51fa..697e042a 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -55,10 +55,19 @@ func sessionReminted(ctx context.Context) bool { return reminted } -// dailyQuotaSkew is how close a 429's Retry-After must land to the next UTC +// dailyQuotaSkew is how late a 429's Retry-After may land after the next UTC // midnight for the rejection to be the exit's daily free-model allowance -// rather than a per-session throttle. It matches the free-quota tracker's rule. -const dailyQuotaSkew = 5 * time.Minute +// rather than a per-session throttle. The observed free-tier reset is a few +// minutes past midnight (5-7 min), so the window has to be wider than the +// tracker's tight 5-minute rule; the per-session throttles seen so far land +// 18+ minutes past, leaving a gap this window stays inside. +const dailyQuotaSkew = 15 * time.Minute + +// freeLimitRepeatWindow is how long a second free-limit rejection on the same +// exit, for a different session, marks that exit as spent. A per-session +// throttle cannot answer two sessions, so a repeat proves the allowance +// belongs to the egress IP and survives a session re-mint. +const freeLimitRepeatWindow = 30 * time.Minute // dailyQuotaReset reports whether resp is the free tier's daily allowance // rejection for this egress, and when that allowance resets. The free-model @@ -89,6 +98,32 @@ func dailyQuotaReset(resp *http.Response, now time.Time) (time.Time, bool) { return reset, true } +// exitFreeLimitReset reports whether the free-limit 429 belongs to the exit +// and when it can serve again. The Retry-After naming the daily reset is the +// fast path. Otherwise only a repeat rejection for a different session proves +// the allowance is per egress: a single rejection may be the session's own +// burn, which the escape retry can clear by re-minting, so parking on it would +// sacrifice a healthy exit. +func exitFreeLimitReset(node *anonymousNode, resp *http.Response, ids identity.RequestIDs, now time.Time) (time.Time, bool) { + if node == nil || node.proxy == nil || !isFreeUsageLimitResponse(resp) { + return time.Time{}, false + } + if reset, daily := dailyQuotaReset(resp, now); daily { + node.proxy.noteFreeLimit(ids.Session, now) + return reset, true + } + if !node.proxy.noteFreeLimit(ids.Session, now) { + return time.Time{}, false + } + retry := parseRetryAfter(resp.Header.Get("Retry-After")) + if retry < time.Minute { + // A repeat with no usable hint still means the exit is spent; bound + // the park so it recovers on its own if the hint was wrong. + retry = time.Hour + } + return now.Add(retry), true +} + // sessionScopedFreeLimit reports whether the attempt's free-tier allowance // rejection belongs to the session rather than to the exit. The gateway // re-mints a session it minted itself and retries once, so such a response must @@ -97,13 +132,13 @@ func dailyQuotaReset(resp *http.Response, now time.Time) (time.Time, bool) { // daily-quota 429 is excluded: that one belongs to the egress IP and is parked // until its reset, not answered by a new session. func sessionScopedFreeLimit(ids identity.RequestIDs, resp *http.Response, err error, now time.Time) bool { - if err != nil || !ids.SessionDerived || !isFreeUsageLimitResponse(resp) { - return false - } - if _, daily := dailyQuotaReset(resp, now); daily { - return false - } - return true + // The free tier ledges the free-model allowance per session id, and every + // exit leaves from the same egress IP (the pool's tunnels differ, the + // observed egress does not), so a free-limit 429 is the same answer on + // every exit. A re-minted session is the only way past it, including for a + // client-supplied session: a burned bucket has no prompt cache to keep. + // The daily reset hint describes that session bucket, not the exit. + return err == nil && isFreeUsageLimitResponse(resp) } // stopBurnedWalk reports whether the anonymous exit walk should stop on this @@ -172,7 +207,7 @@ func rememberSessionEscape(original, escaped identity.RequestIDs) { // locally). The retry's attempt count is added to the total so telemetry keeps // numbering one request's attempts in sequence. func (g *Gateway) escapeBurnedSession(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, resp *http.Response, effectiveRoute models.Route, attempts int) (*http.Response, models.Route, int, error) { - if !ids.SessionDerived || isDiagnosticRequest(ctx) || ctx.Err() != nil { + if isDiagnosticRequest(ctx) || ctx.Err() != nil { return resp, effectiveRoute, attempts, nil } if !sessionScopedFreeLimit(ids, resp, nil, time.Now()) { diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go index 139488cf..79ff454d 100644 --- a/internal/gateway/session_escape_test.go +++ b/internal/gateway/session_escape_test.go @@ -129,14 +129,18 @@ func TestStopBurnedWalk(t *testing.T) { if stopBurnedWalk(withSessionRemint(context.Background()), derived, freeLimit(""), nil, now) { t.Fatal("the re-minted retry must keep walking exits") } - // The exit's own daily allowance is spent (Retry-After = next UTC midnight); - // that is not the session's burn, so the walk must continue to other exits. - if stopBurnedWalk(context.Background(), derived, freeLimit("21600"), nil, now) { - t.Fatal("a daily-quota 429 must keep walking exits") - } + // A daily reset hint still describes the session's own bucket: every exit + // shares one egress, so walking cannot help and the re-mint is the only way + // past it. The original walk must stop too. + if !stopBurnedWalk(context.Background(), derived, freeLimit("21600"), nil, now) { + t.Fatal("a daily-reset 429 must stop the original walk") + } + // Client-supplied sessions are re-minted as well for the same reason: one + // egress means the same answer on every exit, and a burned bucket has no + // prompt cache left to preserve. official := identity.RequestIDs{Session: "ses_y"} - if stopBurnedWalk(context.Background(), official, freeLimit(""), nil, now) { - t.Fatal("an official session must not stop the walk") + if !stopBurnedWalk(context.Background(), official, freeLimit(""), nil, now) { + t.Fatal("an official session's free-limit 429 must stop the walk too") } if stopBurnedWalk(context.Background(), derived, &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok"))}, nil, now) { t.Fatal("a 200 must not stop the walk") @@ -171,6 +175,45 @@ func TestDailyQuotaReset(t *testing.T) { if _, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "21600", `{"error":{"message":"rate limit"}}`), now); ok { t.Fatal("a non-free-limit 429 must not be treated as quota") } + // The observed free-tier reset lands a few minutes past midnight, so the + // window must cover it while still excluding the later session throttles. + if _, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "20700", freeLimitBody), now); !ok { + t.Fatal("a Retry-After five minutes past midnight must be a daily reset") + } + if _, ok := dailyQuotaReset(resp(http.StatusTooManyRequests, "19800", freeLimitBody), now); ok { + t.Fatal("a Retry-After half an hour before midnight must not be a daily reset") + } +} + +func TestExitFreeLimitReset(t *testing.T) { + now := time.Date(2026, 11, 12, 18, 0, 0, 0, time.UTC) + resp := func(retry string) *http.Response { + r := &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Free usage limit reached"}}`))} + if retry != "" { + r.Header.Set("Retry-After", retry) + } + return r + } + proxy := &proxyTransport{index: 0, name: "a"} + node := &anonymousNode{proxy: proxy} + // A single session's rejection may be that session's own burn, which the + // escape retry clears by re-minting, so the exit stays usable. + if _, ok := exitFreeLimitReset(node, resp("20000"), identity.RequestIDs{Session: "ses_a", SessionDerived: true}, now); ok { + t.Fatal("a single session's free-limit 429 must not park the exit") + } + // A rejection for a different session proves the allowance is the egress's. + reset, ok := exitFreeLimitReset(node, resp("20000"), identity.RequestIDs{Session: "ses_b", SessionDerived: true}, now.Add(time.Minute)) + if !ok { + t.Fatal("a second session's free-limit 429 must park the exit") + } + if !reset.After(now) { + t.Fatalf("reset = %s, want after %s", reset, now) + } + // The daily hint still parks on the first rejection. + other := &anonymousNode{proxy: &proxyTransport{index: 1, name: "b"}} + if _, ok := exitFreeLimitReset(other, resp("20700"), identity.RequestIDs{Session: "ses_c"}, now); !ok { + t.Fatal("a Retry-After past midnight must park the exit immediately") + } } func TestCursorSkipsDrainedExits(t *testing.T) { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 78080ba3..a5b12872 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -588,7 +588,12 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) return resp, nil, attempts } - lastResponse = resp + if resp != nil { + // Keep an earlier 429 when this attempt only timed out: the + // client can act on the quota answer, while a transport error + // would surface as a gateway failure. + lastResponse = resp + } lastErr = asProxyUnavailable(node.proxy, err) if err != nil { g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err) @@ -613,24 +618,22 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b halted = true g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) break - } else if reset, daily := dailyQuotaReset(resp, time.Now()); daily { + } else if stopBurnedWalk(ctx, ids, resp, err, time.Now()) { + // The burn follows the session and every exit leaves from the + // same egress, so walking cannot help: stop here and let + // doUpstream re-mint the session and retry once. + burned = true + break + } else if reset, exitScoped := exitFreeLimitReset(node, resp, ids, time.Now()); exitScoped { // The free tier's free-model allowance is per egress IP, and - // this exit has spent it: the Retry-After lands on the next UTC - // midnight. Park the exit until then and keep walking. A new - // session cannot restore an egress's allowance, so the escape - // must not fire for this shape. + // this exit has spent it: the Retry-After lands on the daily + // reset, or a second session was rejected here. Park the exit + // until then and keep walking. A new session cannot restore an + // egress's allowance, so the escape must not fire for this shape. if !isDiagnosticRequest(ctx) { node.proxy.markDrained(reset) } g.logger.Info("free tier exhausted this exit's daily quota; parking it until reset", "component", "upstream", "event", "free_tier_daily_quota_exhausted", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "reset_at", reset.Format(time.RFC3339)) - } else if stopBurnedWalk(ctx, ids, resp, err, time.Now()) { - // The burn follows the session, not the exit: every relay and - // base URL answers this session with the same free-limit 429. - // Stop the walk now so doUpstream re-mints the session and - // retries once instead of spending every exit on a guaranteed - // 429. - burned = true - break } else { g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) } @@ -652,15 +655,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b if ctx.Err() != nil { break } - if sessionScopedFreeLimit(ids, nodeResp, nodeErr, time.Now()) { - // A burned session is not this exit's fault: the escape retry below - // re-mints the session, so cooling the exit would park a healthy - // relay and could leave that retry with nothing to use. - } else if _, daily := dailyQuotaReset(nodeResp, time.Now()); daily { - // The exit answered but spent its own daily free-model allowance. - // That is not a lane outage: parking the exit is enough, and - // counting it as a failure would pause the whole lane while other - // exits still have quota. + if isFreeUsageLimitResponse(nodeResp) { + // A free-limit 429 is the session bucket, not a lane outage: the + // escape below re-mints the session, so cooling the exit would park + // a healthy relay and could leave that retry with nothing to use. if !isDiagnosticRequest(ctx) { g.anonymous.NoteNeutral() } From 8be6845ed2b9dc0f6eff9c9b2989f90fc694eac8 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 19:52:50 +0100 Subject: [PATCH 08/10] gateway: rotate a free-tier session link once it has served a request The free tier meters its free-model bucket per session, and one request at the observed sizes consumes it: across 10 consecutive turns, every session reused from the escape memo answered 429, while 21 fresh sessions answered 200 on the first attempt. Reusing the memoized link therefore bought no prompt-cache affinity, only one guaranteed 429 and one counted attempt per turn. Mark a link spent after it serves a request, and have the escaped-session chain mint and record the next link before the request is sent. The first turn of a conversation still pays one escape, since nothing can predict that the client's session is already burned; later turns go straight to a fresh bucket. --- internal/gateway/session_escape.go | 45 +++++++++++++++++++++++-- internal/gateway/session_escape_test.go | 35 +++++++++++++++++++ internal/gateway/upstream.go | 5 +++ 3 files changed, 82 insertions(+), 3 deletions(-) diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index 697e042a..6357655a 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -159,7 +159,12 @@ type sessionEscapeKey struct{ session, child, parent string } var sessionEscapes = struct { sync.Mutex entries map[sessionEscapeKey]sessionEscapeKey -}{entries: map[sessionEscapeKey]sessionEscapeKey{}} + // spent marks a replacement that has already served a request. The free + // tier meters its free-model bucket per session, and one request at the + // observed sizes consumes it: replaying a spent session only earns a + // guaranteed 429, so the chain advances before the request is sent. + spent map[sessionEscapeKey]bool +}{entries: map[sessionEscapeKey]sessionEscapeKey{}, spent: map[sessionEscapeKey]bool{}} func sessionEscapeKeyOf(ids identity.RequestIDs) sessionEscapeKey { return sessionEscapeKey{ids.Session, ids.ChildSession, ids.ParentSession} @@ -168,19 +173,38 @@ func sessionEscapeKeyOf(ids identity.RequestIDs) sessionEscapeKey { // escapedSession returns ids with every remembered replacement applied. One // conversation can burn more than one session over its life, so the chain is // followed until it ends. The second result reports whether anything changed. +// +// If the chain ends on a replacement that has already served a request, the +// next link is minted here and recorded, so the request is sent on a fresh +// bucket instead of replaying a 429 the upstream is certain to answer. func escapedSession(ids identity.RequestIDs) (identity.RequestIDs, bool) { changed := false // Follow the whole chain: a long conversation burns one bucket per link, // so stopping early would hand back a session that is already spent. for range sessionEscapeLimit { + key := sessionEscapeKeyOf(ids) sessionEscapes.Lock() - value, ok := sessionEscapes.entries[sessionEscapeKeyOf(ids)] + value, ok := sessionEscapes.entries[key] + spent := ok && sessionEscapes.spent[value] sessionEscapes.Unlock() if !ok { break } ids.Session, ids.ChildSession, ids.ParentSession = value.session, value.child, value.parent changed = true + if !spent { + continue + } + // The replacement answered one request already; a second request on + // it is a guaranteed 429. Advance the chain now and reuse the new + // link for the rest of the conversation. + next := ids.WithFreshSession() + ids = next + sessionEscapes.Lock() + sessionEscapes.entries[key] = sessionEscapeKeyOf(next) + delete(sessionEscapes.spent, value) + sessionEscapes.Unlock() + break } return ids, changed } @@ -190,12 +214,23 @@ func escapedSession(ids identity.RequestIDs) (identity.RequestIDs, bool) { // costs the oldest conversations one fresh escape. func rememberSessionEscape(original, escaped identity.RequestIDs) { key := sessionEscapeKeyOf(original) + target := sessionEscapeKeyOf(escaped) sessionEscapes.Lock() defer sessionEscapes.Unlock() if _, exists := sessionEscapes.entries[key]; !exists && len(sessionEscapes.entries) >= sessionEscapeLimit { sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeKey{} + sessionEscapes.spent = map[sessionEscapeKey]bool{} } - sessionEscapes.entries[key] = sessionEscapeKeyOf(escaped) + sessionEscapes.entries[key] = target + delete(sessionEscapes.spent, target) +} + +// markSessionEscapeSpent records that a replacement already served a request, +// so escapedSession rotates it instead of replaying the burn. +func markSessionEscapeSpent(escaped identity.RequestIDs) { + sessionEscapes.Lock() + defer sessionEscapes.Unlock() + sessionEscapes.spent[sessionEscapeKeyOf(escaped)] = true } // escapeBurnedSession retries one routing pass with a re-minted session when @@ -231,6 +266,10 @@ func (g *Gateway) escapeBurnedSession(ctx context.Context, route models.Route, b attempts += used if retryErr == nil && retryResp != nil && retryResp.StatusCode/100 == 2 { rememberSessionEscape(ids, escaped) + // The free tier gave this bucket one request. Marking it spent makes + // the next request in the conversation rotate before sending instead + // of spending an attempt on a guaranteed 429. + markSessionEscapeSpent(escaped) return retryResp, retryRoute, attempts, nil } if retryErr != nil && ctx.Err() != nil { diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go index 79ff454d..faee3404 100644 --- a/internal/gateway/session_escape_test.go +++ b/internal/gateway/session_escape_test.go @@ -16,6 +16,7 @@ func resetSessionEscapes() { sessionEscapes.Lock() defer sessionEscapes.Unlock() sessionEscapes.entries = map[sessionEscapeKey]sessionEscapeKey{} + sessionEscapes.spent = map[sessionEscapeKey]bool{} } func TestIsFreeUsageLimitResponse(t *testing.T) { @@ -78,6 +79,40 @@ func TestSessionEscapeMemoChains(t *testing.T) { } } +func TestSessionEscapeRotatesSpentReplacement(t *testing.T) { + resetSessionEscapes() + first := identity.RequestIDs{Session: "ses_first"} + second := first.WithFreshSession() + rememberSessionEscape(first, second) + markSessionEscapeSpent(second) + + // The replacement already served a request, so the chain must advance + // instead of handing back a bucket that is certain to 429. + got, ok := escapedSession(first) + if !ok { + t.Fatal("expected a remembered replacement") + } + third := second.WithFreshSession() + if got.Session != third.Session { + t.Fatalf("spent replacement was not rotated: got %q want %q", got.Session, third.Session) + } + + // The rotation is recorded, so the next request reuses the same link + // rather than minting another one. + again, _ := escapedSession(first) + if again.Session != third.Session { + t.Fatalf("rotation was not memoized: got %q want %q", again.Session, third.Session) + } + + // Once that link has served a request, the next call rotates again. + markSessionEscapeSpent(third) + fourth := third.WithFreshSession() + next, _ := escapedSession(first) + if next.Session != fourth.Session { + t.Fatalf("second rotation failed: got %q want %q", next.Session, fourth.Session) + } +} + func TestSessionEscapeMemoCaps(t *testing.T) { resetSessionEscapes() for i := 0; i < sessionEscapeLimit+8; i++ { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index a5b12872..fcb4ad7c 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -585,6 +585,11 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration) if err == nil && resp.StatusCode/100 == 2 { g.observeAnonymousResult(ctx, node, resp, nil) + // The free tier meters its bucket per session and this request + // consumed it. Mark the link spent so the next request in the + // conversation rotates before sending instead of spending an + // attempt on a guaranteed 429. + markSessionEscapeSpent(ids) g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) return resp, nil, attempts } From ce6cc0ee915d065fbe94dfb464f9745da00bb4c2 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 20:01:06 +0100 Subject: [PATCH 09/10] gateway: record a session successor after every successful turn A session serves exactly one free-tier request, and the escape memo only existed for chains that had already burned. A conversation starting on the client's own id therefore succeeded once, then had no entry to follow and paid an escape on the second turn. Record the successor when a turn succeeds, so the chain starts on a fresh link from the next turn onward. Also skip links the chain has already used: WithFreshSession is deterministic, so minting from the same key twice returned the same id and the rotation cycled between two spent links. --- internal/gateway/session_escape.go | 42 +++++++++++++++++++--- internal/gateway/session_escape_test.go | 48 +++++++++++++++++++++++++ internal/gateway/upstream.go | 6 ++-- 3 files changed, 89 insertions(+), 7 deletions(-) diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index 6357655a..c1d0953c 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -170,13 +170,32 @@ func sessionEscapeKeyOf(ids identity.RequestIDs) sessionEscapeKey { return sessionEscapeKey{ids.Session, ids.ChildSession, ids.ParentSession} } +// nextUnspentSession returns the next deterministic link after ids that has +// not already served a request. WithFreshSession is deterministic, so minting +// from the same link twice returns the same id; a chain that has advanced +// before must skip the links it already used or it would cycle between two +// spent ids and replay the 429 forever. +func nextUnspentSession(ids identity.RequestIDs) identity.RequestIDs { + next := ids.WithFreshSession() + for range sessionEscapeLimit { + sessionEscapes.Lock() + spent := sessionEscapes.spent[sessionEscapeKeyOf(next)] + sessionEscapes.Unlock() + if !spent { + break + } + next = next.WithFreshSession() + } + return next +} + // escapedSession returns ids with every remembered replacement applied. One // conversation can burn more than one session over its life, so the chain is // followed until it ends. The second result reports whether anything changed. // // If the chain ends on a replacement that has already served a request, the -// next link is minted here and recorded, so the request is sent on a fresh -// bucket instead of replaying a 429 the upstream is certain to answer. +// next unused link is minted here and recorded, so the request is sent on a +// fresh bucket instead of replaying a 429 the upstream is certain to answer. func escapedSession(ids identity.RequestIDs) (identity.RequestIDs, bool) { changed := false // Follow the whole chain: a long conversation burns one bucket per link, @@ -198,7 +217,7 @@ func escapedSession(ids identity.RequestIDs) (identity.RequestIDs, bool) { // The replacement answered one request already; a second request on // it is a guaranteed 429. Advance the chain now and reuse the new // link for the rest of the conversation. - next := ids.WithFreshSession() + next := nextUnspentSession(ids) ids = next sessionEscapes.Lock() sessionEscapes.entries[key] = sessionEscapeKeyOf(next) @@ -225,11 +244,26 @@ func rememberSessionEscape(original, escaped identity.RequestIDs) { delete(sessionEscapes.spent, target) } +// advanceSessionAfterSuccess records that used has served its one request and +// that the next turn should start on its successor. The free tier meters per +// session, so without the recorded successor a conversation reusing the +// client's id would pay a guaranteed 429 on every turn after the first. +func advanceSessionAfterSuccess(used identity.RequestIDs) { + next := nextUnspentSession(used) + rememberSessionEscape(used, next) + markSessionEscapeSpent(used) +} + // markSessionEscapeSpent records that a replacement already served a request, // so escapedSession rotates it instead of replaying the burn. func markSessionEscapeSpent(escaped identity.RequestIDs) { sessionEscapes.Lock() defer sessionEscapes.Unlock() + if len(sessionEscapes.spent) >= sessionEscapeLimit { + // The marks are only an optimization: dropping them costs at most one + // rediscovered 429 per chain, so the map never grows without bound. + sessionEscapes.spent = map[sessionEscapeKey]bool{} + } sessionEscapes.spent[sessionEscapeKeyOf(escaped)] = true } @@ -254,7 +288,7 @@ func (g *Gateway) escapeBurnedSession(ctx context.Context, route models.Route, b original := *resp originalBody, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) httpx.DrainAndClose(resp.Body) - escaped := ids.WithFreshSession() + escaped := nextUnspentSession(ids) if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.Session = escaped.Session } diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go index faee3404..ff46302b 100644 --- a/internal/gateway/session_escape_test.go +++ b/internal/gateway/session_escape_test.go @@ -113,6 +113,54 @@ func TestSessionEscapeRotatesSpentReplacement(t *testing.T) { } } +func TestSessionEscapeAdvancesPastUsedLinks(t *testing.T) { + resetSessionEscapes() + first := identity.RequestIDs{Session: "ses_advance"} + second := first.WithFreshSession() + rememberSessionEscape(first, second) + markSessionEscapeSpent(second) + + // Every turn must reach a link that has not served a request yet. With a + // deterministic mint from the same key, a naive rotation cycles between + // two spent ids and replays the 429 forever. + seen := map[string]bool{second.Session: true} + for turn := 0; turn < 8; turn++ { + got, ok := escapedSession(first) + if !ok { + t.Fatal("expected a remembered replacement") + } + if seen[got.Session] { + t.Fatalf("turn %d reused spent link %q", turn, got.Session) + } + seen[got.Session] = true + markSessionEscapeSpent(got) + } +} + +func TestAdvanceSessionAfterSuccess(t *testing.T) { + resetSessionEscapes() + first := identity.RequestIDs{Session: "ses_conv"} + + // The first turn against the client's own id must leave a successor, or + // the next turn reuses a spent bucket and pays a 429. + advanceSessionAfterSuccess(first) + got, ok := escapedSession(first) + if !ok { + t.Fatal("a served session must have a successor") + } + if got.Session == first.Session { + t.Fatal("the next turn must not reuse the served session") + } + + // The successor is fresh, so it is used as-is; after it serves a request + // the chain must advance again. + advanceSessionAfterSuccess(got) + next, _ := escapedSession(first) + if next.Session == got.Session { + t.Fatalf("chain did not advance after the successor served a request: %q", next.Session) + } +} + func TestSessionEscapeMemoCaps(t *testing.T) { resetSessionEscapes() for i := 0; i < sessionEscapeLimit+8; i++ { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index fcb4ad7c..546638c6 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -586,10 +586,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b if err == nil && resp.StatusCode/100 == 2 { g.observeAnonymousResult(ctx, node, resp, nil) // The free tier meters its bucket per session and this request - // consumed it. Mark the link spent so the next request in the - // conversation rotates before sending instead of spending an + // consumed it. Record the successor now so the next turn in the + // conversation starts on a fresh bucket instead of spending an // attempt on a guaranteed 429. - markSessionEscapeSpent(ids) + advanceSessionAfterSuccess(ids) g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) return resp, nil, attempts } From d2465197563df0e4741f3dcf8157db796dabfacf Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 12 Nov 2026 20:07:17 +0100 Subject: [PATCH 10/10] gateway: keep the spent mark when remembering an escape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The escape path records the original-to-replacement mapping after the retry has already succeeded, and that success marked the replacement spent. Remembering cleared the mark, so the next turn replayed the same replacement and paid another 429 — the exact per-turn cycle the spent mark exists to prevent. --- internal/gateway/session_escape.go | 1 - internal/gateway/session_escape_test.go | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/internal/gateway/session_escape.go b/internal/gateway/session_escape.go index c1d0953c..a0cf0a36 100644 --- a/internal/gateway/session_escape.go +++ b/internal/gateway/session_escape.go @@ -241,7 +241,6 @@ func rememberSessionEscape(original, escaped identity.RequestIDs) { sessionEscapes.spent = map[sessionEscapeKey]bool{} } sessionEscapes.entries[key] = target - delete(sessionEscapes.spent, target) } // advanceSessionAfterSuccess records that used has served its one request and diff --git a/internal/gateway/session_escape_test.go b/internal/gateway/session_escape_test.go index ff46302b..c8a4f788 100644 --- a/internal/gateway/session_escape_test.go +++ b/internal/gateway/session_escape_test.go @@ -161,6 +161,21 @@ func TestAdvanceSessionAfterSuccess(t *testing.T) { } } +func TestRememberSessionEscapeKeepsSpentTarget(t *testing.T) { + resetSessionEscapes() + first := identity.RequestIDs{Session: "ses_seq"} + second := first.WithFreshSession() + markSessionEscapeSpent(second) + // The escape path remembers the mapping after the retry already + // succeeded, so remembering must not unmask a target the success path + // just marked spent. + rememberSessionEscape(first, second) + got, _ := escapedSession(first) + if got.Session == second.Session { + t.Fatalf("spent target %q was reused after being remembered", second.Session) + } +} + func TestSessionEscapeMemoCaps(t *testing.T) { resetSessionEscapes() for i := 0; i < sessionEscapeLimit+8; i++ {