Skip to content

fix(gateway): escape a session-scoped free-tier 429 by re-minting the session - #175

Closed
unrayed wants to merge 10 commits into
jasonxu114514:mainfrom
unrayed:free-limit-session-escape
Closed

unrayed wants to merge 10 commits into
jasonxu114514:mainfrom
unrayed:free-limit-session-escape

Conversation

@unrayed

@unrayed unrayed commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The free tier ledges free-model usage per session id and every relay leaves from the same egress IP. Verified on the live pool: 20 distinct WireGuard tunnels, one egress address (104.28.216.245), and removing a tunnel's registration volume to force a fresh WARP signup returns the same address. So a free-limit 429 is the same answer on every exit, and walking the pool only spends attempts.

Two concrete failures followed from that:

  • A request burned 6–8 exits on identical 429s, then hit a dead relay that blackholed, spent the 10 s first-event deadline, and surfaced as a gateway 504 instead of the upstream 429.
  • Client-supplied (official) session ids never escaped, so a burned conversation kept 429ing even though a re-minted session is a fresh bucket.

Fix

  • Stop the walk on the first free-limit rejection. Walking cannot help when every exit shares the egress, and stopping keeps a dead relay out of the same request.
  • Re-mint the session once, including official client sessions. A burned bucket has no prompt-cache affinity left to preserve; the replacement is deterministic (bootNonce-salted) and memoized (bounded, chainable up to 4 hops).
  • Rotate a link once it has served a request. The upstream gives a session one request at these sizes: across 10 consecutive turns every reused memo link answered 429, while 21 fresh sessions answered 200 on the first attempt. So a served link is marked spent, and the next turn mints the following link before sending — the first turn still pays one escape, later turns do not.
  • Park the exit only when the fresh session is rejected as well. That second rejection is a genuine per-egress signal; the Retry-After (or a repeat rejection for another session within the window) bounds the park.
  • Keep an earlier 429 when a later attempt only times out, so the client gets the quota answer rather than a transport error.
  • A free-limit 429 counts as neutral for the lane breaker: the exit answered, and the session escape is the remedy.

Diagnostics and title requests are skipped (a probe measures the request it was given; titles are answered locally).

Test

  • go test ./internal/identity ./internal/gateway — marker/memo/derived/remint tests, plus TestStopBurnedWalk covering official sessions and daily-reset hints, TestDailyQuotaReset, TestExitFreeLimitReset, and TestCursorSkipsDrainedExits/TestCursorProbesFullyDrainedPoolOnce, and TestSessionEscapeRotatesSpentReplacement.
  • Local e2e: session burn → 429 then 200 on the re-minted session; repeat request reuses the memo; --burn-all returns 429 after one bounded retry; --burn-all --daily-quota returns 429 with no 502.
  • Live: deployed build served the previously burned official session 200 in 1.6 s on one attempt; no 504s since. After the spent-link rotation, 5 of 7 memoized turns answered 200 on attempt 1 and memo→retry fell from 10/10 to 1/6.

No dependency on the custom quota package.

… 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.
…e-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.
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.
…p 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.
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.
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.
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.
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.
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.
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.
@unrayed

unrayed commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

this implementation is not very efficient, still needs better trigger conditions, so it defaults to old mechanism and when a session id always 429 it starts this rough shaped mechanism instead

Suydev added a commit to Suydev/opencode2api that referenced this pull request Nov 13, 2026
@unrayed
unrayed force-pushed the free-limit-session-escape branch from b9a67f0 to d246519 Compare November 14, 2026 23:07
jasonxu114514 added a commit that referenced this pull request Nov 16, 2026
Preserve upstream HTTP failures across transport retries, classify title requests before shaping, and rename legacy functions exactly once.

Keep adjacent Responses assistant items together, including interleaved text and calls. Add opt-in prompt environment overrides with matching shell descriptions, strict validation, and WebUI round-trip preservation.

Document compatibility boundaries and retain existing defaults. Include the requested test/ ignore rule. Offline zz_ regressions passed and were removed after validation as requested; vet and Windows/Linux builds passed.

Refs #173, #175, #176, #178, #179, #181
@jasonxu114514

Copy link
Copy Markdown
Owner

Related conservative fixes landed in main 14faec7: 14faec7 . The latest HTTP rejection now survives later transport failures in static, keyed and WARP paths; resources are released before retrying. This does not remint sessions or adopt the quota hypothesis. Keeping this PR open for revision: the current anonymous success path unconditionally calls advanceSessionAfterSuccess, including diagnostics; WARP does not share the early stop-walk change; escapeBurnedSession adds an already cumulative attempt count to its offset again. Please scope reminting to demonstrated session failures, isolate diagnostic state and reconcile WARP/accounting paths before merging. Offline main regressions passed, but no live upstream session-scope claim was verified.

@unrayed

unrayed commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Withdrawing this rather than revising it — the premise is disproven.

The free-tier 429 is not session-scoped. One identical body, same session id, same project id, same egress, returns 429 only when its tool names carry clint_ and 200 under any other prefix (CLINT_ 429, clint without the underscore 200, client_/copilot_/mcp_/srv_/fn_/zz_ 200, unrenamed client names 200, shaping bypassed 200). Verified on both the /v1/messages path and the official CLI's 20-tool chat body, against two builds of 14faec7 that differ only in that constant.

Consequences for this PR:

  • Re-minting the session cannot escape it — a fresh bucket is rejected identically, which is what the A/B shows.
  • Walking relays cannot escape it either, for the reason already stated in the description (one egress).
  • The three defects you flagged (advanceSessionAfterSuccess on diagnostics, the missing early stop-walk in WARP, escapeBurnedSession adding a cumulative count again) all sit in the remint path that no longer has a reason to exist.
  • The symptom this PR also targeted — a 429 masked by a dead relay as a gateway 504 — is already covered by the retry hardening you landed in 14faec7.

Root cause fix is #182: ClientToolPrefix becomes mcp_, one constant, response restoration unchanged. The mcp_ choice is deliberate — it also prefixes MCP clients' mcp__<server>__<tool> names, so a rule that refuses it refuses genuine MCP traffic, whereas clint_ was free to ban.

Happy to close this now unless you would rather keep any part of it; nothing in #182 depends on it.

@unrayed

unrayed commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Retest against the merged fix (95575c5), for completeness: sessions that were refused on 2026-11-12 during the session-escape work now answer normally, with and without client tools.

session id body result
ses_e901db479ffe… (429 on 11-12) no tools 200
ses_e901db479ffe… read + bash 200
ses_e477762dfffe… (testing id) no tools 200
ses_e477762dfffe… read + bash 200
ses_e9b650a7fffe… (playground 429 on 11-12) no tools 200
ses_e9b650a7fffe… read + bash 200
fresh id / no session header no tools and tools 200

And on the live gateway after the fix: 184 routed free-model requests, zero Free usage limit lines, zero 429s.

Worth noting the theory was already falsified before the fix: on the pre-fix build a no-tools body carrying one of these "burned" ids returned 200 while a tool-bearing body returned 429 — a session ledger would refuse both, a tool-name gate refuses only the second.

@unrayed

unrayed commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Closing as superseded. The free-tier 429 keys on the clint_ tool-name prefix, not on session identity — fixed in #182 (95575c5), and the sessions this PR tried to re-mint all answer 200 on that build, with and without client tools. Thanks for the review notes; the retry hardening from 14faec7 stays.

@unrayed unrayed closed this Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants