Skip to content

fix: keep /v1/responses encrypted continuation on same auth#1796

Open
1saifj wants to merge 5 commits intorouter-for-me:mainfrom
1saifj:fix/responses-encrypted-content-affinity
Open

fix: keep /v1/responses encrypted continuation on same auth#1796
1saifj wants to merge 5 commits intorouter-for-me:mainfrom
1saifj:fix/responses-encrypted-content-affinity

Conversation

@1saifj
Copy link

@1saifj 1saifj commented Mar 2, 2026

Fixes #1793.

Root Cause

/v1/responses HTTP 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" with encrypted_content, that blob is upstream-context-bound (org/account/provider). If round-robin switched auth/provider, upstream returned 400 invalid_encrypted_content (could not be decrypted or parsed).

Fix

  • Added responses auth-affinity store in sdk/api/handlers/openai/openai_responses_affinity.go:
    • maps previous_response_id -> selected_auth_id
    • maps reasoning.encrypted_content (hashed) -> selected_auth_id
  • openai_responses_handlers now:
    • resolves pinned auth from request affinity keys before execution
    • captures selected auth ID via callback when not pinned
    • persists affinity from non-stream and SSE responses
  • Added guarded recovery paths:
    • if pinned continuation fails and request contains encrypted reasoning input, strip encrypted reasoning and retry once without pinning (allows fallback to healthy auth/provider)
    • if unpinned request still returns invalid_encrypted_content, strip encrypted reasoning and retry once
    • same bootstrap recovery behavior for streaming /v1/responses before first chunk

Tests

Added/updated tests in sdk/api/handlers/openai/openai_responses_affinity_test.go:

  • TestResponsesAffinityPinsAuthUsingEncryptedContent
  • TestResponsesEncryptedContentRecoveryStripsReasoningInput
  • TestResponsesPinnedAuthFailureFallsBackUnpinned
  • TestResponsesStreamingPinnedAuthFailureFallsBackUnpinned

Also updated stream error test for the chunk observer hook signature.

Verification

  • go test ./sdk/api/handlers/openai
  • go test ./sdk/api/handlers/...

Copilot AI review requested due to automatic review settings March 2, 2026 15:57
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, 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 /v1/responses could fail due to authentication switching between turns. Previously, the system was stateless, and a round-robin authentication selection could inadvertently change the provider for a continuation, leading to errors with upstream-context-bound encrypted payloads. The fix introduces an authentication affinity store that pins continuation requests to the original authentication ID, ensuring consistent provider usage. Additionally, a recovery mechanism is implemented to handle and retry requests that initially fail due to invalid encrypted content.

Highlights

  • Auth Affinity Store: Introduced a new in-memory store to maintain authentication affinity for /v1/responses endpoints, mapping response IDs and encrypted content hashes to specific authentication IDs.
  • Pinned Authentication: Implemented logic to resolve and pin the authentication ID for continuation requests based on previous_response_id or encrypted reasoning input, ensuring subsequent requests use the same provider.
  • Guarded Recovery: Added a recovery mechanism for non-streaming requests that encounter invalid_encrypted_content errors, which strips encrypted reasoning input and retries the request once.
  • SSE Affinity Persistence: Enhanced streaming responses (SSE) to remember authentication affinity by extracting encrypted content from output items and associating them with the selected authentication ID.

🧠 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
  • sdk/api/handlers/openai/openai_responses_affinity.go
    • Added a new responsesAuthAffinityStore to manage authentication IDs based on response IDs and encrypted content hashes.
    • Implemented functions to resolvePinnedAuthIDForResponses, rememberResponsesAuthAffinity, and rememberResponsesAuthAffinityFromSSE.
    • Included utility functions like isInvalidEncryptedContentError, stripEncryptedReasoningInput, and extractReasoningEncrypted.
  • sdk/api/handlers/openai/openai_responses_affinity_test.go
    • Added new test cases to verify that continuation requests maintain authentication affinity when encrypted content is present.
    • Included tests for the guarded recovery path, ensuring encrypted reasoning input is stripped on failure and the request is retried.
  • sdk/api/handlers/openai/openai_responses_handlers.go
    • Updated handleNonStreamingResponse to use the new affinity logic and guarded recovery for invalid_encrypted_content errors.
    • Modified handleStreamingResponse to resolve and pin authentication IDs for streaming requests and to persist affinity from SSE chunks.
    • Refactored the non-streaming execution into a new executeNonStreamingWithAffinity helper function.
    • Adjusted forwardResponsesStream to accept a callback for processing SSE chunks.
  • sdk/api/handlers/openai/openai_responses_handlers_stream_error_test.go
    • Updated the call signature for forwardResponsesStream in an existing test to match the new function definition.
Activity
  • No specific activity (comments, reviews, progress updates) has been recorded for this pull request since its creation.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +292 to +297
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)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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 byEncryptedHash

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/responses execution 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.

Comment on lines +188 to +197
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)
})
}
Copy link

Copilot AI Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +276 to +287
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 {
Copy link

Copilot AI Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +125 to +127
func isInvalidEncryptedContentError(errMsg *interfaces.ErrorMessage) bool {
if errMsg == nil || errMsg.Error == nil || errMsg.StatusCode != 400 {
return false
Copy link

Copilot AI Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
@1saifj
Copy link
Author

1saifj commented Mar 2, 2026

Addressed the review findings in follow-up commit 5818fca.

  1. Pinned auth failure (auth_not_found): recovery is now broader than 400 invalid_encrypted_content. If a pinned continuation request fails and contains encrypted reasoning input, handler strips encrypted reasoning and retries once without pinning, allowing fallback to other auth/provider.
  2. Streaming recovery: same strip+unpin recovery now applies to /v1/responses streaming bootstrap errors (before first payload).
  3. Regression coverage: added tests for the exact exhaustion scenario:
    • TestResponsesPinnedAuthFailureFallsBackUnpinned
    • TestResponsesStreamingPinnedAuthFailureFallsBackUnpinned

This keeps affinity for happy path but no longer blocks fallback when the pinned upstream is exhausted.

@1saifj
Copy link
Author

1saifj commented Mar 2, 2026

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:

  • go test ./sdk/api/handlers/openai
  • go test ./sdk/api/handlers/...

@1saifj
Copy link
Author

1saifj commented Mar 2, 2026

Addressed Gemini high-severity cache eviction feedback in the current branch:

  • Removed full-map reset when maxEntries is exceeded.
  • Implemented bounded partial eviction (reduce to ~75% capacity) after TTL cleanup for both affinity maps.
  • This avoids sudden total affinity loss and reduces continuation miss spikes under load.

Implementation is in sdk/api/handlers/openai/openai_responses_affinity.go pruneLocked().

@1saifj
Copy link
Author

1saifj commented Mar 2, 2026

Follow-up updates pushed in commit 5b786c9 to close the remaining encrypted-continuation gaps for #1793.

What was added:

  • Recovery now strips both encrypted reasoning and previous_response_id, including previous_response_id-only cases.
  • Streaming recovery broadened to the same context predicate and extended for post-first-chunk terminal encrypted-content failures when assistant content has not started.
  • Responses auth-affinity store now persists to disk (env-configurable path) so restart does not drop affinity.
  • Added tests:
    • TestResponsesStreamingPreviousResponseIDOnlyPinnedFailureFallsBackUnpinned
    • TestResponsesStreamingPostFirstChunkInvalidEncryptedFallsBackWhenNoContentYet
    • TestResponsesAffinityStorePersistsAcrossRestart

Validation rerun:

  • go test -count=1 ./sdk/api/handlers/openai
  • go test -count=1 ./sdk/api/handlers/...
  • go test -race -count=1 ./sdk/api/handlers/openai

This PR now covers the provider-switch + exhaustion + restart paths described in #1793.

Copy link
Collaborator

@luispater luispater left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. I’m requesting changes mainly around:

  1. The streaming recovery gate is too eager. responsesStreamChunkHasAssistantContent() treats response.output_item.added for a message as "content started", but our translators emit that before response.content_part.added / response.output_text.delta. That means a failure can skip recovery even though no user-visible token has been sent yet.

  2. 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.

  3. 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

@1saifj
Copy link
Author

1saifj commented Mar 7, 2026

Addressed in a27df47.

  1. The streaming recovery gate now waits for actual user-visible assistant output instead of treating response.output_item.added for a message as content-started. The handler only marks content as started on visible response.output_text.* payloads (or refusal/audio output), so a failure after lifecycle-only events can still recover.

  2. The streaming recovery path no longer splices two upstream attempts into one SSE response. Pre-visible chunks are buffered first; if the upstream fails before anything visible is flushed, the handler can still retry safely. Once the stream has been flushed to the client, it does not restart the upstream anymore and returns a terminal stream error instead.

  3. The default shared persistence file under os.TempDir() is removed. Responses auth affinity now persists only when CLIPROXY_RESPONSES_AFFINITY_PATH is explicitly configured, so separate CLIProxyAPI instances do not share affinity state by default.

I also added/updated regression coverage for the message-added-before-content case and the no-splice/no-leak behavior, then reran:

  • GOCACHE=/tmp/cliproxy-go-build GOTMPDIR=/tmp go test ./sdk/api/handlers/openai -count=1
  • GOCACHE=/tmp/cliproxy-go-build GOTMPDIR=/tmp go test ./sdk/api/handlers/... -count=1
  • GOCACHE=/tmp/cliproxy-go-build GOTMPDIR=/tmp go test -race ./sdk/api/handlers/openai -count=1

@1saifj 1saifj requested a review from luispater March 7, 2026 21:33
@1saifj
Copy link
Author

1saifj commented Mar 9, 2026

@luispater Please if it is OK merge it. Issues happen all around using gpt 5.4 and 5.3 on my machine.
Screenshot 2026-03-09 at 9 47 42 PM

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.

400 invalid_encrypted_content on /v1/responses after provider switch (OpenAI -> Azure)

3 participants