fix: keep /v1/responses encrypted continuation on same auth#1796
fix: keep /v1/responses encrypted continuation on same auth#17961saifj wants to merge 5 commits intorouter-for-me:mainfrom
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request addresses an issue where continuation requests to Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces auth affinity for /v1/responses to ensure continuation requests use the same authentication, which is a solid improvement. The implementation uses an in-memory cache and includes a retry mechanism for invalid_encrypted_content errors. The code is well-structured and includes good test coverage for the new functionality. My main feedback is on the cache eviction strategy, which could be improved to be less disruptive under high load. Please see the specific comment for details.
| if len(s.byResponseID) > s.maxEntries { | ||
| s.byResponseID = make(map[string]responsesAuthAffinityEntry, s.maxEntries/2) | ||
| } | ||
| if len(s.byEncryptedHash) > s.maxEntries { | ||
| s.byEncryptedHash = make(map[string]responsesAuthAffinityEntry, s.maxEntries/2) | ||
| } |
There was a problem hiding this comment.
The current cache pruning strategy when maxEntries is exceeded is to reset the entire map. This will cause a sudden loss of all stored affinity information, which could lead to a wave of affinity misses and failures for continuation requests until the cache is repopulated. This could negatively impact service availability under high load. The comment on line 290 is also misleading, as resetting the map does not "clear oldest pressure".
A less disruptive approach would be to implement a more granular eviction strategy. For example, you could evict a random portion of the entries. Since there's no "oldest" tracking, random eviction would be a simple improvement over clearing the entire map.
A proper LRU cache would be the ideal solution here for more predictable behavior, but even a simple random eviction of a portion of the map would be a significant improvement.
For example, to evict 25% of entries randomly:
// Evict 25% of the entries randomly
if len(s.byResponseID) > s.maxEntries {
targetSize := s.maxEntries * 3 / 4
for k := range s.byResponseID {
if len(s.byResponseID) <= targetSize {
break
}
delete(s.byResponseID, k)
}
}
// Same for byEncryptedHashThere was a problem hiding this comment.
Pull request overview
This PR fixes OpenAI /v1/responses continuation failures caused by round-robin auth/provider switching across turns by introducing an auth-affinity mechanism keyed by previous_response_id and reasoning.encrypted_content, plus a guarded non-stream recovery retry for invalid_encrypted_content.
Changes:
- Added an in-memory responses auth-affinity store (response ID + encrypted-content hash → auth ID) with TTL + max-entries bounds.
- Updated streaming and non-streaming
/v1/responsesexecution to pin auth when affinity exists and to record affinity from response payloads/SSE chunks. - Added a non-stream recovery path that strips encrypted reasoning input and retries once on
invalid_encrypted_content.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| sdk/api/handlers/openai/openai_responses_handlers.go | Pins/records auth selection for streaming and non-streaming responses; adds one-shot recovery retry; extends stream forwarder hook to observe chunks. |
| sdk/api/handlers/openai/openai_responses_affinity.go | Implements the auth-affinity store and helpers (resolve/remember, SSE parsing, encrypted stripping). |
| sdk/api/handlers/openai/openai_responses_affinity_test.go | Adds tests covering affinity pinning and the recovery retry behavior. |
| sdk/api/handlers/openai/openai_responses_handlers_stream_error_test.go | Updates test callsite for the new forwardResponsesStream signature. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| selectedAuthID := "" | ||
| pinnedAuthID := resolvePinnedAuthIDForResponses(rawJSON) | ||
| if pinnedAuthID != "" { | ||
| cliCtx = handlers.WithPinnedAuthID(cliCtx, pinnedAuthID) | ||
| selectedAuthID = pinnedAuthID | ||
| } else { | ||
| cliCtx = handlers.WithSelectedAuthIDCallback(cliCtx, func(authID string) { | ||
| selectedAuthID = strings.TrimSpace(authID) | ||
| }) | ||
| } |
There was a problem hiding this comment.
selectedAuthID is mutated inside WithSelectedAuthIDCallback, but that callback can be invoked from a different goroutine than the handler (e.g., ExecuteStreamWithAuthManager performs bootstrap retries inside its internal goroutine, which will re-run auth selection and call the callback). This introduces a data race and can also cause the wrong auth ID to be used when calling rememberResponsesAuthAffinityFromSSE (the successful retry’s auth may differ from the initial attempt). Use synchronization (e.g., atomic.Value/mutex) for reads/writes of selectedAuthID, or plumb the selected auth ID back through a channel/struct owned by the streaming goroutine so the handler reads a stable value for the stream that actually produced bytes.
| func (s *responsesAuthAffinityStore) pruneLocked(now time.Time) { | ||
| for key, entry := range s.byResponseID { | ||
| if now.After(entry.expiresAt) { | ||
| delete(s.byResponseID, key) | ||
| } | ||
| } | ||
| for key, entry := range s.byEncryptedHash { | ||
| if now.After(entry.expiresAt) { | ||
| delete(s.byEncryptedHash, key) | ||
| } | ||
| } | ||
| if len(s.byResponseID) <= s.maxEntries && len(s.byEncryptedHash) <= s.maxEntries { |
There was a problem hiding this comment.
pruneLocked scans both maps on every insert (rememberResponseID / rememberEncrypted), making each write O(n) with n up to ~8k entries. Under high request volume this can become a noticeable CPU hotspot. Consider pruning less frequently (e.g., track nextPruneAt and only scan when it’s elapsed), or evicting incrementally (LRU/clock) rather than full-map scans on every write.
| func isInvalidEncryptedContentError(errMsg *interfaces.ErrorMessage) bool { | ||
| if errMsg == nil || errMsg.Error == nil || errMsg.StatusCode != 400 { | ||
| return false |
There was a problem hiding this comment.
isInvalidEncryptedContentError compares errMsg.StatusCode to the literal 400. Elsewhere in this package the code consistently uses http.StatusBadRequest, which is clearer and avoids magic numbers. Prefer http.StatusBadRequest here as well.
|
Addressed the review findings in follow-up commit 5818fca.
This keeps affinity for happy path but no longer blocks fallback when the pinned upstream is exhausted. |
|
Applied reviewer cleanup suggestion in commit 8e71041: removed the redundant second non-stream recovery block so there is now a single strip+retry path. Validation rerun:
|
|
Addressed Gemini high-severity cache eviction feedback in the current branch:
Implementation is in sdk/api/handlers/openai/openai_responses_affinity.go pruneLocked(). |
|
Follow-up updates pushed in commit 5b786c9 to close the remaining encrypted-continuation gaps for #1793. What was added:
Validation rerun:
This PR now covers the provider-switch + exhaustion + restart paths described in #1793. |
luispater
left a comment
There was a problem hiding this comment.
Thanks for the PR. I’m requesting changes mainly around:
-
The streaming recovery gate is too eager.
responsesStreamChunkHasAssistantContent()treatsresponse.output_item.addedfor a message as "content started", but our translators emit that beforeresponse.content_part.added/response.output_text.delta. That means a failure can skip recovery even though no user-visible token has been sent yet. -
The post-first-chunk retry path can splice two upstream attempts into one SSE stream. The first chunk is flushed to the client, and then the handler restarts the stream on error, so clients may see lifecycle events / response IDs from two different attempts in one response.
-
The affinity store now persists by default to a single file under
os.TempDir(). Multiple CLIProxyAPI instances on the same host will share and overwrite this state, which can leak affinity across deployments and pin continuations to stale or wrong auth IDs.
Tested: go test ./sdk/api/handlers/openai
|
Addressed in
I also added/updated regression coverage for the message-added-before-content case and the no-splice/no-leak behavior, then reran:
|
|
@luispater Please if it is OK merge it. Issues happen all around using gpt 5.4 and 5.3 on my machine. |

Fixes #1793.
Root Cause
/v1/responsesHTTP requests were stateless across turns. Provider/auth selection uses round-robin, so continuation turns could switch auth between requests.When a continuation payload includes
input[].type="reasoning"withencrypted_content, that blob is upstream-context-bound (org/account/provider). If round-robin switched auth/provider, upstream returned400 invalid_encrypted_content(could not be decrypted or parsed).Fix
sdk/api/handlers/openai/openai_responses_affinity.go:previous_response_id -> selected_auth_idreasoning.encrypted_content (hashed) -> selected_auth_idopenai_responses_handlersnow:invalid_encrypted_content, strip encrypted reasoning and retry once/v1/responsesbefore first chunkTests
Added/updated tests in
sdk/api/handlers/openai/openai_responses_affinity_test.go:TestResponsesAffinityPinsAuthUsingEncryptedContentTestResponsesEncryptedContentRecoveryStripsReasoningInputTestResponsesPinnedAuthFailureFallsBackUnpinnedTestResponsesStreamingPinnedAuthFailureFallsBackUnpinnedAlso updated stream error test for the chunk observer hook signature.
Verification
go test ./sdk/api/handlers/openaigo test ./sdk/api/handlers/...