feat(gateway): pause the anonymous lane after repeated failures

A flagged free-tier exit keeps answering 403 (IP-level abuse detection)
and retrying only extends the penalty. Add an optional lane-level circuit
breaker, configured with models.anonymous_backoff:

- threshold consecutive failed anonymous attempts, or one 403/429, pause
  the whole lane for base_hours, doubling on every further trip up to
  max_hours;
- while paused, no proxy is drawn and no upstream request is made, so
  routing falls straight through to the authenticated tiers;
- a successful attempt closes the breaker and restores the free lane;
- absent config leaves behavior unchanged;
- availability probes honour the breaker instead of refreshing the block.
This commit is contained in:
rock committed 2026-10-20 23:02:10 +08:00
1 parent f0f064f31d
commit 8cc5e96489
6 files changed
+155 -4

No files matched your search

+4 -1
View File
@@ -217,6 +217,8 @@ The routing sequence is:
Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate keys. Other 4xx responses end the current tier; another available tier may still be tried.
When the free tier is blocked for the whole deployment (an IP-level `403` abuse response), retrying only extends the penalty, so an optional lane-level circuit breaker can stop the probing. With `models.anonymous_backoff` configured, `threshold` consecutive failed anonymous attempts, or a single `403`/`429` (an explicit block signal), pause the whole anonymous lane for `base_hours`, doubling on every further trip up to `max_hours`. While paused, requests skip the lane entirely: no proxy is drawn, no upstream request is made, and routing goes straight to the authenticated tiers. The first attempt after the window expires probes once; success closes the breaker and restores the free lane, failure opens the next, longer window. The block is absent, and so the breaker is off, by default.
Requests are encoded for each tier's own protocol. With `performance.first_event_timeout_seconds` enabled, a successful SSE response is held until the first complete data event. A timeout or disconnect before that event uses the existing key/proxy retry budget; comments do not satisfy the timeout. Once released downstream, the stream is never replayed. The default is `0` (disabled); try `15` seconds for upstreams that accept requests but send no events. This bounds the first event, not the first text token, and does not apply to System One. Rotation aliases use their separate `rotation.first_output_seconds` timeout. A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay.
When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane.
@@ -245,7 +247,7 @@ A stable session hash selects the preferred key or anonymous proxy. Send an expl
Sessions and projects the gateway derives itself are scoped to the caller's server key, so different keys never share an upstream session, preferred key, or anonymous proxy. Official OpenCode sessions (`ses_…`) sent by the client are kept as-is. Without an explicit ID, the system prompt and the first user message are used as a seed. Conversations under the same key that begin with the same system prompt and content can therefore still share affinity; give users who must stay isolated their own server keys. Changing pool membership can change the selected node.
Cooldowns grow exponentially up to eight times `performance.failure_cooldown_seconds`, and a longer `Retry-After` is honored. If every authenticated key is cooling down, routing may try the key whose cooldown ends first. Anonymous nodes still in cooldown are skipped.
Cooldowns grow exponentially up to eight times `performance.failure_cooldown_seconds`, and a longer `Retry-After` is honored. A configured `models.anonymous_backoff` breaker is a separate lane-level guard: it pauses the whole anonymous lane for hours, while these cooldowns stay per exit and short. If every authenticated key is cooling down, routing may try the key whose cooldown ends first. Anonymous nodes still in cooldown are skipped.
## Configuration reference
@@ -268,6 +270,7 @@ See [config.example.json](config.example.json) for a complete starting configura
| `models.refresh_seconds` | `300`; minimum 1. |
| `models.protocols` | `{}`; per-model native protocol overrides. |
| `models.free_only` | `false`; expose and route only free models, even with Zen or Go keys. |
| `models.anonymous_backoff` | Absent (off); `{threshold, base_hours, max_hours}`, defaulting to `6`, `1`, `24`. |
| `reasoning.effort` | Empty (off); `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, or `none`. |
| `reasoning.effort_by_model` | `{}`; per-model overrides of `reasoning.effort`. |
+43
View File
@@ -100,6 +100,46 @@ type ModelsConfig struct {
// FreeOnly limits discovery and routing to free models, even when Zen or
// Go keys could serve paid ones. Free models may still fall back to keys.
FreeOnly bool `json:"free_only"`
// AnonymousBackoff configures a circuit breaker for the keyless lane: after
// Threshold consecutive failed attempts, or immediately on a 403 or 429,
// the lane pauses for BaseHours, doubling on every further trip up to
// MaxHours. An absent block leaves the lane unpaused, which is the previous
// behavior.
AnonymousBackoff *AnonymousBackoffConfig `json:"anonymous_backoff,omitempty"`
}
// AnonymousBackoffConfig tunes the keyless lane's circuit breaker. Zero fields
// take the defaults shown in Normalize.
type AnonymousBackoffConfig struct {
Threshold int `json:"threshold,omitempty"`
BaseHours int `json:"base_hours,omitempty"`
MaxHours int `json:"max_hours,omitempty"`
}
// Normalize fills the defaults and rejects nonsensical windows.
func (b *AnonymousBackoffConfig) Normalize() error {
if b == nil {
return nil
}
if b.Threshold == 0 {
b.Threshold = 6
}
if b.BaseHours == 0 {
b.BaseHours = 1
}
if b.MaxHours == 0 {
b.MaxHours = 24
}
if b.Threshold < 1 {
return errors.New("models.anonymous_backoff.threshold must be at least 1")
}
if b.BaseHours < 1 {
return errors.New("models.anonymous_backoff.base_hours must be at least 1")
}
if b.MaxHours < b.BaseHours {
return errors.New("models.anonymous_backoff.max_hours must not be smaller than base_hours")
}
return nil
}
// LoggingConfig sets the minimum log level (debug, info, warn or error) and
@@ -306,6 +346,9 @@ func Normalize(path string, cfg Config) (Config, error) {
return Config{}, fmt.Errorf("unsupported proxy scheme %q", u.Scheme)
}
}
if err := cfg.Models.AnonymousBackoff.Normalize(); err != nil {
return Config{}, err
}
for model, protocol := range cfg.Models.Protocols {
if model == "" || !wire.Valid(wire.Protocol(protocol)) {
return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol)
+14 -1
View File
@@ -119,13 +119,26 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics) (*G
transports: transports,
zenNodes: zenNodes,
goNodes: goNodes,
anonymous: anonymousPool(cfg.Anonymous, transports, cooldown),
anonymous: anonymousPool(cfg.Anonymous, transports, cooldown, anonymousBackoffFromConfig(cfg.Models.AnonymousBackoff)),
catalog: catalog,
monitor: monitor,
attemptTimeout: attemptDeadline(cfg),
}, nil
}
// anonymousBackoffFromConfig converts the configured hours into the breaker's
// thresholds and durations. A nil block disables the breaker (threshold 0).
func anonymousBackoffFromConfig(cfg *config.AnonymousBackoffConfig) anonymousBackoff {
if cfg == nil {
return anonymousBackoff{}
}
return anonymousBackoff{
threshold: int32(cfg.Threshold),
base: time.Duration(cfg.BaseHours) * time.Hour,
max: time.Duration(cfg.MaxHours) * time.Hour,
}
}
// Handler returns the gateway's HTTP API: the server-key authenticated /v1
// model, inference and System One routes plus the open /healthz, wrapped in
// panic recovery.
+70 -2
View File
@@ -53,6 +53,20 @@ type anonymousNodes struct {
next atomic.Uint64
cooldown time.Duration
hasPool bool
// breaker stops the whole lane after repeated failures instead of poking
// a flagged upstream forever: after backoff.threshold consecutive failed
// attempts the lane pauses for backoff.base, doubling every further trip
// (one strike per trip) up to backoff.max. A success closes the breaker.
backoff anonymousBackoff
breakerUntil atomic.Int64
breakerStrikes atomic.Int32
consecutive atomic.Int32
}
type anonymousBackoff struct {
threshold int32
base time.Duration
max time.Duration
}
type anonymousNode struct {
@@ -73,8 +87,8 @@ type anonymousCursor struct {
// anonymousPool builds one anonymous node per proxy transport, or an empty
// pool when the anonymous tier is disabled.
func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Duration) *anonymousNodes {
pool := &anonymousNodes{cooldown: cooldown}
func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Duration, backoff anonymousBackoff) *anonymousNodes {
pool := &anonymousNodes{cooldown: cooldown, backoff: backoff}
if !enabled || transports == nil {
return pool
}
@@ -119,6 +133,60 @@ func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor {
return anonymousCursor{pool: p, start: start}
}
// Paused reports whether the breaker currently holds the lane shut.
func (p *anonymousNodes) Paused() bool {
if p == nil {
return false
}
until := p.breakerUntil.Load()
return until != 0 && time.Now().UnixNano() < until
}
// NoteSuccess closes the breaker and forgets the strikes.
func (p *anonymousNodes) NoteSuccess() {
if p == nil {
return
}
p.consecutive.Store(0)
p.breakerStrikes.Store(0)
p.breakerUntil.Store(0)
}
// NoteFailure records one failed attempt. It reports the pause window when the
// consecutive-failure threshold trips the breaker.
func (p *anonymousNodes) NoteFailure() (time.Duration, bool) {
if p == nil || p.backoff.threshold < 1 {
return 0, false
}
if p.consecutive.Add(1) < p.backoff.threshold {
return 0, false
}
return p.trip()
}
// ForceOpen trips the breaker immediately. A 403 or 429 from the anonymous
// upstream is a clear "blocked" signal (abuse detection, fingerprint gate or
// region lock), and continuing to probe only extends the block, so it does
// not wait for the consecutive-failure threshold.
func (p *anonymousNodes) ForceOpen() (time.Duration, bool) {
if p == nil || p.backoff.threshold < 1 {
return 0, false
}
return p.trip()
}
// trip opens the breaker for the next backoff window and returns it.
func (p *anonymousNodes) trip() (time.Duration, bool) {
p.consecutive.Store(0)
strike := p.breakerStrikes.Add(1)
pause := p.backoff.base << min(strike-1, 30)
if pause > p.backoff.max || pause <= 0 {
pause = p.backoff.max
}
p.breakerUntil.Store(time.Now().Add(pause).UnixNano())
return pause, true
}
// Next returns the next node to try. Its first pass visits every node once
// from the cursor's start and returns each healthy, non-cooling static proxy
// and each rotating proxy-pool transport (#pool) it reaches, so healthy nodes
+5
View File
@@ -88,6 +88,11 @@ func probePayload(model string, protocol wire.Protocol, effort string, v1 bool)
// when every lane reported it; any other failure keeps the result
// inconclusive.
func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult {
if g.anonymous.Paused() {
// The breaker is open; probing now would just refresh the upstream's
// abuse window.
return probeResult{reason: "anonymous_paused", attempted: false}
}
if !g.catalog.IsFreeModel(model) {
return probeResult{reason: "not_free"}
}
+19
View File
@@ -303,6 +303,11 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
// tiers. It returns the last response (body still open), else the last error,
// plus the number of attempts made.
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
// The breaker holds the lane shut for an hour-scale window after repeated
// failures: poking a flagged upstream again would only extend the block.
if g.anonymous.Paused() {
return nil, errors.New("anonymous lane paused by its circuit breaker"), 0
}
var lastResponse *http.Response
var lastErr error
cursor := g.anonymous.CursorFor(ids.Session)
@@ -1136,8 +1141,22 @@ func (g *Gateway) observeAnonymousResult(ctx context.Context, node *anonymousNod
g.syncProxyResult(ctx, node.proxy, status, err)
if err == nil && status/100 == 2 {
g.anonymous.MarkSuccess(node)
g.anonymous.NoteSuccess()
} else {
g.anonymous.MarkFailure(node, resp, err)
var pause time.Duration
var tripped bool
if status == http.StatusForbidden || status == http.StatusTooManyRequests {
// Clearly blocked: stop probing immediately instead of letting
// further requests extend the upstream's abuse window.
pause, tripped = g.anonymous.ForceOpen()
} else {
pause, tripped = g.anonymous.NoteFailure()
}
if tripped {
g.logger.Warn("anonymous lane circuit breaker opened",
"component", "upstream", "event", "anonymous_breaker_open", "status", status, "paused_for", pause.String())
}
}
}