fix(gateway): keep portable reasoning summaries during compaction recovery

Same-account recovery now strips ciphertext while rewriting readable
summaries as developer messages, continues to session reset when the
stripped retry still returns 400, and only rotates accounts after
reasoning_recovery_failed. Drop Diagnostic substring matching so
unrelated 400s do not scan the account pool.
This commit is contained in:
haswysa committed 2026-08-26 08:05:37 +08:00
1 parent 1de4c8152d
commit 2408b67ddb
6 files changed
+209 -52

No files matched your search

@@ -243,6 +243,39 @@ func TestHTTPUpstreamFailureLeavesPaymentRecoveryKindToBilling(t *testing.T) {
}
}
func TestRetryableResponseRotatesOnlyOnReasoningRecoveryFailedWarning(t *testing.T) {
failedHeader := make(http.Header)
failedHeader.Set("X-Grok2API-Compatibility-Warnings", "reasoning_encrypted_content_downgraded,reasoning_recovery_failed")
failed := &provider.Response{
StatusCode: http.StatusBadRequest,
Header: failedHeader,
Body: io.NopCloser(strings.NewReader(`{"error":"Could not decode the compaction blob"}`)),
}
if !isRetryableResponse(failed, accountdomain.ProviderBuild) {
t.Fatal("reasoning_recovery_failed 400 must rotate accounts")
}
plain := &provider.Response{
StatusCode: http.StatusBadRequest,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"error":"Could not decode the compaction blob"}`)),
Diagnostic: &provider.DiagnosticResponse{Body: []byte(`{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`)},
}
if isRetryableResponse(plain, accountdomain.ProviderBuild) {
t.Fatal("plain compaction 400 must not rotate accounts without reasoning_recovery_failed")
}
unrelated := &provider.Response{
StatusCode: http.StatusBadRequest,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"error":"invalid request history"}`)),
Diagnostic: &provider.DiagnosticResponse{Body: []byte(`{"error":"could not decode request json"}`)},
}
if isRetryableResponse(unrelated, accountdomain.ProviderBuild) {
t.Fatal("unrelated 400 must not match encrypted_content/decode substrings")
}
}
func TestRetryableResponseHonorsUpstreamRetryVeto(t *testing.T) {
response := &provider.Response{
StatusCode: http.StatusInternalServerError,
@@ -2096,17 +2096,8 @@ func isReasoningRecoveryFailedResponse(response *provider.Response) bool {
if response == nil {
return false
}
warnings := response.Header.Get("X-Grok2api-Compatibility-Warnings")
if strings.Contains(warnings, "reasoning_recovery_failed") {
return true
}
if response.Diagnostic != nil {
lower := strings.ToLower(string(response.Diagnostic.Body))
if strings.Contains(lower, "compaction blob") ||
strings.Contains(lower, "encrypted_content") ||
strings.Contains(lower, "could not decrypt") ||
strings.Contains(lower, "could not decode") ||
strings.Contains(lower, "invalid_encrypted_content") {
for _, value := range strings.Split(response.Header.Get("X-Grok2API-Compatibility-Warnings"), ",") {
if strings.TrimSpace(value) == "reasoning_recovery_failed" {
return true
}
}
@@ -404,7 +404,7 @@ func TestNativeBuildHistoryItemsArePreservedAndSanitized(t *testing.T) {
}
}
func TestReasoningWithoutEncryptedContentBecomesBoundary(t *testing.T) {
func TestReasoningWithoutEncryptedContentBecomesPortableSummary(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":[
{"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}},
@@ -422,7 +422,11 @@ func TestReasoningWithoutEncryptedContentBecomesBoundary(t *testing.T) {
items := request["input"].([]any)
first := items[0].(map[string]any)
if first["type"] != "message" || first["role"] != "developer" {
t.Fatalf("unencrypted reasoning should become boundary, got %#v", first)
t.Fatalf("unencrypted reasoning should become portable summary, got %#v", first)
}
text := first["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(text, "who am I") || strings.Contains(text, "omitted") {
t.Fatalf("portable reasoning text = %q", text)
}
if items[1].(map[string]any)["content"] != "hi" {
t.Fatalf("assistant history = %#v", items[1])
@@ -259,18 +259,20 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin
}
func sanitizeReasoningInput(item map[string]any) map[string]any {
// Grok Build Responses API 中 type: "reasoning" 严格用于不透明密文回放,
// 上游强制要求携带合法的 encrypted_content。
// 若缺少 encrypted_content,则降级为 developer 兼容边界消息,杜绝向 Grok 发送裸 reasoning。
encrypted, ok := item["encrypted_content"].(string)
if ok && strings.TrimSpace(encrypted) != "" {
converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content")
converted["type"] = "reasoning"
// Keep ciphertext-backed reasoning native. Summary-only items are rewritten
// as developer messages so the readable plan survives without sending a
// bare type=reasoning item that Grok Build may reject.
converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content")
converted["type"] = "reasoning"
if encrypted, ok := converted["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" {
if _, exists := converted["summary"]; !exists {
converted["summary"] = []any{}
}
return converted
}
if portable, ok := portableReasoningSummaryMessage(converted); ok {
return portable
}
return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.")
}
@@ -16,10 +16,6 @@ var reasoningDecodeFailureMarkers = [][]byte{
[]byte("could not decode the compaction blob"),
[]byte("could not decrypt the provided encrypted_content"),
[]byte("invalid_encrypted_content"),
[]byte("could not be decrypted or parsed"),
[]byte("could not decrypt"),
[]byte("decode the compaction blob"),
[]byte("compaction blob"),
}
type reasoningRecoveryOutcome struct {
@@ -51,12 +47,14 @@ func (o reasoningRecoveryOutcome) appendWarnings(header http.Header) {
// recoverReasoningDecodeFailure handles only the upstream's explicit
// pre-generation opaque-reasoning decode rejection. Recovery never changes
// credential or Build/XAI plane:
// 1. remove replayed encrypted_content and retry in the same session;
// 2. when the same decode error remains (or no opaque item exists), clear the
// server-side session identity and retry once with the full portable input.
// 1. remove replayed encrypted_content, keep any readable summary as a
// portable developer message, and retry in the same session;
// 2. when a 400 remains (or no opaque item exists), clear the server-side
// session identity and retry once with the full portable input.
//
// If recovery is unsuccessful, the original 400 is returned so the Gateway
// does not rotate accounts or obscure the first failure.
// If recovery is unsuccessful, the original 400 is returned with
// reasoning_recovery_failed so the Gateway can rotate accounts. The Provider
// itself never changes credential.
func (a *Adapter) recoverReasoningDecodeFailure(
ctx context.Context,
request provider.ResponseResourceRequest,
@@ -109,12 +107,23 @@ func (a *Adapter) recoverReasoningDecodeFailure(
a.logReasoningRecovery(request, base, "encrypted_content", "rate_limited", retry.StatusCode, nil)
return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}
}
retryStatus := retry.StatusCode
sameDecodeFailure, inspectErr := responseHasReasoningDecodeFailure(retry)
if inspectErr != nil || !sameDecodeFailure {
a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retry.StatusCode, inspectErr)
if inspectErr != nil {
a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, inspectErr)
return original, requestURL, reasoningRecoveryOutcome{failed: true}
}
a.logReasoningRecovery(request, base, "encrypted_content", "decode_error_persisted", retry.StatusCode, nil)
if retryStatus != http.StatusBadRequest {
a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, nil)
return original, requestURL, reasoningRecoveryOutcome{failed: true}
}
if sameDecodeFailure {
a.logReasoningRecovery(request, base, "encrypted_content", "decode_error_persisted", retryStatus, nil)
} else {
// Stripping ciphertext can reword the 400 (for example a bare
// reasoning item). Keep going to session reset instead of aborting.
a.logReasoningRecovery(request, base, "encrypted_content", "retry_still_400", retryStatus, nil)
}
}
if !canResetReasoningSession(request, portableBody) {
@@ -244,12 +253,11 @@ func isReasoningDecodeFailure(body []byte) bool {
return false
}
// stripReasoningEncryptedContent removes undecodable opaque reasoning and compaction
// states so Grok Build does not fail on server-side decryption.
// In Grok Build Responses API, type: "reasoning" is exclusively used for opaque encrypted replay;
// sending type: "reasoning" without encrypted_content is rejected by the upstream.
// Any reasoning item (whether it contains encrypted_content or bare summary) is removed, and any
// compaction item is converted to a compatibility boundary message.
// stripReasoningEncryptedContent removes undecodable opaque reasoning and
// compaction ciphertext so Grok Build does not fail on server-side decryption.
// Readable reasoning summaries are kept as portable developer messages; empty
// encrypted-only reasoning items are dropped. Foreign compaction blobs become
// a boundary note because this gateway cannot decrypt them.
func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
var payload map[string]any
if json.Unmarshal(body, &payload) != nil {
@@ -267,17 +275,32 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
rebuilt = append(rebuilt, raw)
continue
}
itemType := stringField(item, "type")
if itemType == "reasoning" {
switch stringField(item, "type") {
case "reasoning":
encrypted, hasEncrypted := item["encrypted_content"].(string)
if !hasEncrypted || strings.TrimSpace(encrypted) == "" {
if portable, ok := portableReasoningSummaryMessage(item); ok {
changed = true
rebuilt = append(rebuilt, portable)
continue
}
rebuilt = append(rebuilt, raw)
continue
}
changed = true
continue
}
if itemType == "compaction" {
if portable, ok := portableReasoningSummaryMessage(item); ok {
rebuilt = append(rebuilt, portable)
}
case "compaction":
changed = true
if portable, ok := portableReasoningSummaryMessage(item); ok {
rebuilt = append(rebuilt, portable)
continue
}
rebuilt = append(rebuilt, compatibilityBoundaryMessage("A prior compacted context could not be decoded by upstream. Continue from the retained conversation messages."))
continue
default:
rebuilt = append(rebuilt, raw)
}
rebuilt = append(rebuilt, raw)
}
if !changed {
return body, false
@@ -290,6 +313,28 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
return encoded, true
}
func portableReasoningSummaryMessage(item map[string]any) (map[string]any, bool) {
text := reasoningPortableText(item)
if text == "" {
return nil, false
}
return compatibilityBoundaryMessage("Prior model reasoning summary:\n" + text), true
}
func reasoningPortableText(item map[string]any) string {
var parts []string
for _, field := range []string{"summary", "content"} {
values, _ := item[field].([]any)
for _, raw := range values {
part, _ := raw.(map[string]any)
if text := strings.TrimSpace(stringField(part, "text")); text != "" {
parts = append(parts, text)
}
}
}
return strings.Join(parts, "\n")
}
func appendCompatibilityWarning(header http.Header, warning string) {
if header == nil || strings.TrimSpace(warning) == "" {
return
@@ -34,17 +34,26 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T
var payload struct {
Input []map[string]any `json:"input"`
}
if json.Unmarshal(downgraded, &payload) != nil || len(payload.Input) != 3 {
if json.Unmarshal(downgraded, &payload) != nil || len(payload.Input) != 4 {
t.Fatalf("downgraded = %s, len=%d", downgraded, len(payload.Input))
}
if payload.Input[0]["type"] != "message" || payload.Input[0]["role"] != "developer" {
t.Fatalf("compaction boundary item = %#v", payload.Input[0])
summary := payload.Input[0]
if summary["type"] != "message" || summary["role"] != "developer" {
t.Fatalf("readable reasoning = %#v", summary)
}
if payload.Input[1]["encrypted_content"] != "message-value" {
t.Fatalf("non-reasoning encrypted content changed: %#v", payload.Input[1])
summaryText, _ := summary["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(summaryText, "readable") || strings.Contains(summaryText, "omitted") {
t.Fatalf("readable reasoning text = %q", summaryText)
}
if payload.Input[2]["role"] != "user" {
t.Fatalf("user message changed: %#v", payload.Input[2])
compaction := payload.Input[1]
if compaction["type"] != "message" || compaction["role"] != "developer" {
t.Fatalf("compaction boundary item = %#v", compaction)
}
if payload.Input[2]["encrypted_content"] != "message-value" {
t.Fatalf("non-reasoning encrypted content changed: %#v", payload.Input[2])
}
if payload.Input[3]["role"] != "user" {
t.Fatalf("user message changed: %#v", payload.Input[3])
}
}
@@ -470,6 +479,79 @@ func (reasoningRecoveryFallbackMarker) MarkBuildAPIFallback(context.Context, uin
return nil
}
func TestRecoverReasoningDecodeFailureKeepsReadableSummary(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
call := calls.Add(1)
data, _ := io.ReadAll(request.Body)
if call == 1 {
if !strings.Contains(string(data), `"encrypted_content":"opaque"`) {
t.Fatalf("first body = %s", data)
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
}
if strings.Contains(string(data), `"encrypted_content"`) || strings.Contains(string(data), `"type":"reasoning"`) {
t.Fatalf("retry still has opaque reasoning: %s", data)
}
if !strings.Contains(string(data), "do not touch Y") {
t.Fatalf("retry dropped readable summary: %s", data)
}
return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil
})
response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "session-1",
Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[{"type":"summary_text","text":"do not touch Y"}],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`),
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if calls.Load() != 2 || response.StatusCode != http.StatusOK || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_encrypted_content_downgraded") {
t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), response.StatusCode, response.Header.Get("X-Grok2API-Compatibility-Warnings"))
}
}
func TestRecoverReasoningDecodeFailureContinuesToSessionResetWhenStripRewords400(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
call := calls.Add(1)
data, _ := io.ReadAll(request.Body)
switch call {
case 1:
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
case 2:
if strings.Contains(string(data), `"encrypted_content"`) || request.Header.Get("x-grok-session-id") == "" {
t.Fatalf("opaque downgrade body=%s headers=%#v", data, request.Header)
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"invalid request history"}`), nil
case 3:
if strings.Contains(string(data), `"encrypted_content"`) || strings.Contains(string(data), `"prompt_cache_key"`) || request.Header.Get("x-grok-session-id") != "" {
t.Fatalf("session reset body=%s headers=%#v", data, request.Header)
}
return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil
default:
t.Fatalf("unexpected call %d", call)
return nil, nil
}
})
response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "session-1",
Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`),
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
if calls.Load() != 3 || response.StatusCode != http.StatusOK || !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") || !strings.Contains(warnings, "reasoning_session_reset") {
t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), response.StatusCode, warnings)
}
}
func TestRecoverReasoningDecodeFailureCompactionBlob(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32