-
Notifications
You must be signed in to change notification settings - Fork 11.1k
fix(openai): recover from invalid reasoning signatures #6392
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ygcaicn
wants to merge
4
commits into
QuantumNous:main
Choose a base branch
from
ygcaicn:codex/fix-thinking-signature-invalid
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
050667e
fix(openai): recover from invalid reasoning signatures
ygcaicn b762d8c
feat(channel): gate reasoning signature fallback
ygcaicn 30478c5
fix(openai): reserve signature recovery retry
ygcaicn cabc256
fix(openai): preserve recovery across channel fallback
ygcaicn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/constant" | ||
| "github.com/QuantumNous/new-api/dto" | ||
| relaycommon "github.com/QuantumNous/new-api/relay/common" | ||
| relayconstant "github.com/QuantumNous/new-api/relay/constant" | ||
| "github.com/QuantumNous/new-api/service" | ||
| "github.com/QuantumNous/new-api/types" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestShouldRetryOpenAIReasoningSignatureInvalid(t *testing.T) { | ||
| originalRedisEnabled := common.RedisEnabled | ||
| common.RedisEnabled = false | ||
| t.Cleanup(func() { | ||
| common.RedisEnabled = originalRedisEnabled | ||
| }) | ||
|
|
||
| newContext := func(encryptedContent string) *gin.Context { | ||
| ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) | ||
| input := []byte(`[{"type":"reasoning","encrypted_content":"` + encryptedContent + `"}]`) | ||
| _, _, err := service.PrepareOpenAIResponsesReasoningInput(ctx, input, true) | ||
| require.NoError(t, err) | ||
| return ctx | ||
| } | ||
| invalidSignature := types.WithOpenAIError(types.OpenAIError{ | ||
| Code: string(types.ErrorCodeThinkingSignatureInvalid), | ||
| Message: "encrypted content could not be verified", | ||
| }, http.StatusBadRequest) | ||
|
|
||
| openAIResponses := &relaycommon.RelayInfo{ | ||
| RelayMode: relayconstant.RelayModeResponses, | ||
| ChannelMeta: &relaycommon.ChannelMeta{ | ||
| ApiType: constant.APITypeOpenAI, | ||
| ChannelSetting: dto.ChannelSettings{ | ||
| EnableThinkingSignatureFallback: true, | ||
| }, | ||
| }, | ||
| } | ||
| ctx := newContext("controller-openai-responses") | ||
| assert.True(t, shouldRetryOpenAIReasoningSignatureInvalid(ctx, openAIResponses, invalidSignature)) | ||
| assert.False(t, shouldRetryOpenAIReasoningSignatureInvalid(ctx, openAIResponses, invalidSignature), "the fallback adds only one retry") | ||
|
|
||
| nonOpenAI := &relaycommon.RelayInfo{ | ||
| RelayMode: relayconstant.RelayModeResponses, | ||
| ChannelMeta: &relaycommon.ChannelMeta{ | ||
| ApiType: constant.APITypeCodex, | ||
| }, | ||
| } | ||
| assert.False(t, shouldRetryOpenAIReasoningSignatureInvalid(newContext("controller-codex"), nonOpenAI, invalidSignature)) | ||
|
|
||
| disabledOpenAI := &relaycommon.RelayInfo{ | ||
| RelayMode: relayconstant.RelayModeResponses, | ||
| ChannelMeta: &relaycommon.ChannelMeta{ | ||
| ApiType: constant.APITypeOpenAI, | ||
| }, | ||
| } | ||
| assert.False(t, shouldRetryOpenAIReasoningSignatureInvalid(newContext("controller-disabled-openai"), disabledOpenAI, invalidSignature)) | ||
|
|
||
| openAIChat := &relaycommon.RelayInfo{ | ||
| RelayMode: relayconstant.RelayModeChatCompletions, | ||
| ChannelMeta: &relaycommon.ChannelMeta{ | ||
| ApiType: constant.APITypeOpenAI, | ||
| ChannelSetting: dto.ChannelSettings{ | ||
| EnableThinkingSignatureFallback: true, | ||
| }, | ||
| }, | ||
| } | ||
| assert.False(t, shouldRetryOpenAIReasoningSignatureInvalid(newContext("controller-openai-chat"), openAIChat, invalidSignature)) | ||
|
|
||
| otherError := types.WithOpenAIError(types.OpenAIError{ | ||
| Code: "invalid_request_error", | ||
| Message: "bad request", | ||
| }, http.StatusBadRequest) | ||
| assert.False(t, shouldRetryOpenAIReasoningSignatureInvalid(newContext("controller-other-error"), openAIResponses, otherError)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| package service | ||
|
|
||
| import ( | ||
| "crypto/sha256" | ||
| "encoding/hex" | ||
| "fmt" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/logger" | ||
| "github.com/QuantumNous/new-api/pkg/cachex" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/samber/hot" | ||
| "github.com/tidwall/gjson" | ||
| "github.com/tidwall/sjson" | ||
| ) | ||
|
|
||
| const ( | ||
| ginKeyOpenAIReasoningEncryptedContentHash = "openai_reasoning_encrypted_content_hash" | ||
| ginKeyOpenAIReasoningDropEncryptedContent = "openai_reasoning_drop_encrypted_content" | ||
| ginKeyOpenAIReasoningDropApplied = "openai_reasoning_drop_applied" | ||
| ginKeyOpenAIReasoningSignatureRetryAttempted = "openai_reasoning_signature_retry_attempted" | ||
|
|
||
| openAIReasoningFallbackCacheNamespace = "new-api:openai_reasoning_fallback:v1" | ||
| openAIReasoningFallbackCacheCapacity = 100_000 | ||
| openAIReasoningFallbackTTL = 24 * time.Hour | ||
| ) | ||
|
|
||
| var ( | ||
| openAIReasoningFallbackCacheOnce sync.Once | ||
| openAIReasoningFallbackCache *cachex.HybridCache[int] | ||
| ) | ||
|
|
||
| func getOpenAIReasoningFallbackCache() *cachex.HybridCache[int] { | ||
| openAIReasoningFallbackCacheOnce.Do(func() { | ||
| openAIReasoningFallbackCache = cachex.NewHybridCache[int](cachex.HybridCacheConfig[int]{ | ||
| Namespace: cachex.Namespace(openAIReasoningFallbackCacheNamespace), | ||
| Redis: common.RDB, | ||
| RedisEnabled: func() bool { | ||
| return common.RedisEnabled && common.RDB != nil | ||
| }, | ||
| RedisCodec: cachex.IntCodec{}, | ||
| Memory: func() *hot.HotCache[string, int] { | ||
| return hot.NewHotCache[string, int](hot.LRU, openAIReasoningFallbackCacheCapacity). | ||
| WithTTL(openAIReasoningFallbackTTL). | ||
| WithJanitor(). | ||
| Build() | ||
| }, | ||
| }) | ||
| }) | ||
| return openAIReasoningFallbackCache | ||
| } | ||
|
|
||
| // PrepareOpenAIResponsesReasoningInput applies the Responses API fallback when | ||
| // the selected channel enables it or the current request already entered the | ||
| // recovery flow. The latter keeps the forced retry effective if routing falls | ||
| // back to another OpenAI channel that has the setting disabled. A later, | ||
| // independent request still needs an enabled channel before consulting the | ||
| // learned conversation cache. | ||
| func PrepareOpenAIResponsesReasoningInput(c *gin.Context, input []byte, channelEnabled bool) ([]byte, int, error) { | ||
| dropEncryptedContent := c.GetBool(ginKeyOpenAIReasoningDropEncryptedContent) | ||
| if !channelEnabled && !dropEncryptedContent { | ||
| return input, 0, nil | ||
| } | ||
|
|
||
| items := gjson.ParseBytes(input) | ||
| if !items.IsArray() { | ||
| return input, 0, nil | ||
| } | ||
|
|
||
| firstEncryptedContent := "" | ||
| items.ForEach(func(_, item gjson.Result) bool { | ||
| if item.Get("type").String() != "reasoning" { | ||
| return true | ||
| } | ||
| encryptedContent := item.Get("encrypted_content") | ||
| if encryptedContent.Exists() && encryptedContent.Type == gjson.String && encryptedContent.String() != "" { | ||
| firstEncryptedContent = encryptedContent.String() | ||
| return false | ||
| } | ||
| return true | ||
| }) | ||
| if firstEncryptedContent == "" { | ||
| return input, 0, nil | ||
| } | ||
|
|
||
| hash := sha256.Sum256([]byte(firstEncryptedContent)) | ||
| cacheKey := hex.EncodeToString(hash[:]) | ||
| c.Set(ginKeyOpenAIReasoningEncryptedContentHash, cacheKey) | ||
|
|
||
| if !dropEncryptedContent { | ||
| _, found, err := getOpenAIReasoningFallbackCache().Get(cacheKey) | ||
| if err != nil { | ||
| logger.LogWarn(c, fmt.Sprintf("openai reasoning fallback cache get failed: %v", err)) | ||
| } else if found { | ||
| dropEncryptedContent = true | ||
| c.Set(ginKeyOpenAIReasoningDropEncryptedContent, true) | ||
| if err := getOpenAIReasoningFallbackCache().SetWithTTL(cacheKey, 1, openAIReasoningFallbackTTL); err != nil { | ||
| logger.LogWarn(c, fmt.Sprintf("openai reasoning fallback cache ttl refresh failed: %v", err)) | ||
| } | ||
| } | ||
| } | ||
| if !dropEncryptedContent { | ||
| return input, 0, nil | ||
| } | ||
|
|
||
| result := input | ||
| removed := 0 | ||
| index := 0 | ||
| var deleteErr error | ||
| items.ForEach(func(_, item gjson.Result) bool { | ||
| if item.Get("type").String() == "reasoning" && item.Get("encrypted_content").Exists() { | ||
| result, deleteErr = sjson.DeleteBytes(result, fmt.Sprintf("%d.encrypted_content", index)) | ||
| if deleteErr != nil { | ||
| return false | ||
| } | ||
| removed++ | ||
| } | ||
| index++ | ||
| return true | ||
| }) | ||
| if deleteErr != nil { | ||
| return input, 0, fmt.Errorf("remove reasoning encrypted_content: %w", deleteErr) | ||
| } | ||
| if removed > 0 { | ||
| c.Set(ginKeyOpenAIReasoningDropApplied, true) | ||
| } | ||
| return result, removed, nil | ||
| } | ||
|
|
||
| // MarkOpenAIReasoningSignatureInvalid records the conversation fallback and | ||
| // enables one immediate retry for the current request. The cache write is best | ||
| // effort; the current retry still removes encrypted_content if Redis is down. | ||
| func MarkOpenAIReasoningSignatureInvalid(c *gin.Context) bool { | ||
| if c == nil || c.GetBool(ginKeyOpenAIReasoningDropApplied) || c.GetBool(ginKeyOpenAIReasoningSignatureRetryAttempted) { | ||
| return false | ||
| } | ||
| cacheKey := c.GetString(ginKeyOpenAIReasoningEncryptedContentHash) | ||
| if cacheKey == "" { | ||
| return false | ||
| } | ||
|
|
||
| c.Set(ginKeyOpenAIReasoningSignatureRetryAttempted, true) | ||
| c.Set(ginKeyOpenAIReasoningDropEncryptedContent, true) | ||
| if err := getOpenAIReasoningFallbackCache().SetWithTTL(cacheKey, 1, openAIReasoningFallbackTTL); err != nil { | ||
| logger.LogWarn(c, fmt.Sprintf("openai reasoning fallback cache set failed: %v", err)) | ||
| } | ||
| return true | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.