Merge pull request #1022 from buddhism5080/fix/forward-upstream-compact-blobs

fix(cli): forward original compact blobs and surface decode 400s
This commit is contained in:
Chenyme authored and GitHub committed 2026-08-31 15:44:29 +08:00
commit d4f13aa47f
7 files changed
+221 -72

No files matched your search

+1 -1
View File
@@ -299,7 +299,7 @@ Web can be weakly linked one-to-one with matching Build and Console accounts. Li
### Codex, Claude Code, and prompt caching
Responses and Messages support streaming, tools, reasoning, multi-turn sessions, and compaction. Stable client session signals are preserved for Grok Build prompt-cache affinity. Cache hits still require a compatible upstream account and an unchanged prompt prefix. A still-decryptable compaction summary from this gateway instance is expanded even if the session or PromptCacheKey remaps; foreign or undecodable blobs remain a compatibility boundary.
Responses and Messages support streaming, tools, reasoning, multi-turn sessions, and compaction. Stable client session signals are preserved for Grok Build prompt-cache affinity. Cache hits still require a compatible upstream account and an unchanged prompt prefix. A still-decryptable `g2a_compact_v1` summary from this gateway instance is expanded even if the session or PromptCacheKey remaps; an invalid prefixed blob is rejected with 400. Other compaction blobs keep their original `encrypted_content` when forwarded as upstream state, and any Build rejection is returned to the client.
Responses and Chat Completions report OpenAI-style total input. Messages reports Anthropic-style uncached input and cache reads separately. Audits retain total and cached input for billing reconciliation.
+1 -1
View File
@@ -297,7 +297,7 @@ Web 可与对应的 Build、Console 建立一对一弱关联。关联只共享
### Codex、Claude Code 与 Prompt Cache
Responses 与 Messages 支持流式、工具、推理、多轮会话和 compact。客户端会话信号会保持稳定,用于 Grok Build Prompt Cache 亲和;实际命中仍要求上游账号兼容且请求前缀未变化。同一网关实例内,仍可解密的 compact 摘要在 session / PromptCacheKey 漂移后也会展开;无法解密的外源 blob 仍视为兼容边界。
Responses 与 Messages 支持流式、工具、推理、多轮会话和 compact。客户端会话信号会保持稳定,用于 Grok Build Prompt Cache 亲和;实际命中仍要求上游账号兼容且请求前缀未变化。同一网关实例内,仍可解密的 `g2a_compact_v1` 摘要在 session / PromptCacheKey 漂移后也会展开;带该前缀但无法解码的 blob 会返回 400。其他 compact blob 作为上游原始状态转发时会保留原始 `encrypted_content`;若 Build 拒绝,该错误会原样返回客户端。
Responses 与 Chat Completions 按 OpenAI 语义报告输入总量;Messages 按 Anthropic 语义分开报告未缓存输入和缓存读取。审计保留输入总量与缓存部分,用于计费对账。
@@ -247,17 +247,14 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
request.NormalizedMetadata.ReasoningEffort = conversationOptions.ReasoningEffort
}
} else {
var foreignCompactions, driftedCompactions int
body, foreignCompactions, driftedCompactions, err = expandGatewayCompactionHistory(body, a.compaction, request.PromptCacheKey)
var driftedCompactions int
body, driftedCompactions, err = expandGatewayCompactionHistory(body, a.compaction, request.PromptCacheKey)
if err != nil {
return invalidResponsesResponse(err), nil
}
body, toolCompatibility, err = normalizeResponsesRequestWithMetadata(body, request.Model, request.NormalizedMetadata)
if toolCompatibility != nil {
compactionRequested = toolCompatibility.compactionRequested
if foreignCompactions > 0 {
toolCompatibility.addWarning("foreign_compaction_omitted")
}
if driftedCompactions > 0 {
toolCompatibility.addWarning("compaction_session_drifted")
}
@@ -87,18 +87,20 @@ func (c *gatewayCompactionCodec) decode(session, blob string) (summary string, o
}
// expandGatewayCompactionHistory restores gateway-owned remote-v2 state to a
// portable developer message. Foreign OpenAI/Claude/Gemini blobs are never
// forwarded to Grok Build: its decoder cannot decrypt those provider states.
func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, session string) ([]byte, int, int, error) {
// portable developer message. Client compaction blobs without the gateway
// prefix are treated as upstream original compact state and forwarded as-is.
// A still-decryptable g2a_compact_v1 blob is expanded locally; an invalid
// prefixed blob is rejected as a local 400. If Build rejects an original blob,
// that upstream error is returned to the client.
func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, session string) ([]byte, int, error) {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body, 0, 0, nil // normalizeResponsesRequest owns the public JSON error.
return body, 0, nil // normalizeResponsesRequest owns the public JSON error.
}
items, ok := payload["input"].([]any)
if !ok {
return body, 0, 0, nil
return body, 0, nil
}
foreign := 0
drifted := 0
changed := false
for index, raw := range items {
@@ -109,28 +111,27 @@ func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec,
blob, _ := item["encrypted_content"].(string)
summary, owned, sessionDrifted, err := codec.decode(session, blob)
if err != nil {
foreign++
items[index] = compatibilityBoundaryMessage("A prior compacted context could not be decoded by this gateway instance. Continue from the retained conversation messages.")
changed = true
return body, drifted, &responsesRequestError{
Message: "The gateway compaction blob could not be decoded. Ensure it is unmodified and was issued by this gateway.",
Param: fmt.Sprintf("input[%d].encrypted_content", index),
Code: "invalid_compaction_blob",
}
}
if !owned {
continue
}
if owned {
items[index] = gatewayCompactionSummaryMessage(summary)
if sessionDrifted {
drifted++
}
} else {
foreign++
items[index] = compatibilityBoundaryMessage("A compacted context created by another provider cannot be decoded by Grok Build. Continue from the retained conversation messages.")
items[index] = gatewayCompactionSummaryMessage(summary)
if sessionDrifted {
drifted++
}
changed = true
}
if !changed {
return body, 0, 0, nil
return body, 0, nil
}
payload["input"] = items
encoded, err := json.Marshal(payload)
return encoded, foreign, drifted, err
return encoded, drifted, err
}
// prepareGatewayCompactionSample mirrors Grok Build full-replace
@@ -1,6 +1,7 @@
package cli
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
@@ -51,16 +52,16 @@ func TestGatewayCompactionLifecycle(t *testing.T) {
t.Fatalf("content type = %q", contentType)
}
blob = compactionBlobFromSSE(t, stream)
expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "session-1")
expanded, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "session-1")
if err != nil {
t.Fatal(err)
}
if foreign != 0 || drifted != 0 || !strings.Contains(string(expanded), "This session is being continued") || strings.Contains(string(expanded), `"type":"compaction"`) || !strings.Contains(string(expanded), `"role":"user"`) {
t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, drifted)
if drifted != 0 || !strings.Contains(string(expanded), "This session is being continued") || strings.Contains(string(expanded), `"type":"compaction"`) || !strings.Contains(string(expanded), `"role":"user"`) {
t.Fatalf("expanded = %s, drifted = %d", expanded, drifted)
}
mismatched, unusable, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "other-session")
if err != nil || unusable != 0 || drifted != 1 || strings.Contains(string(mismatched), blob) || strings.Contains(string(mismatched), "could not be decoded") || !strings.Contains(string(mismatched), "This session is being continued") {
t.Fatalf("session mismatch expansion = %s, unusable = %d, drifted = %d, err = %v", mismatched, unusable, drifted, err)
mismatched, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "other-session")
if err != nil || drifted != 1 || strings.Contains(string(mismatched), blob) || strings.Contains(string(mismatched), "could not be decoded") || !strings.Contains(string(mismatched), "This session is being continued") {
t.Fatalf("session mismatch expansion = %s, drifted = %d, err = %v", mismatched, drifted, err)
}
}
@@ -95,17 +96,42 @@ func TestForwardResponseRetainsSessionDriftedCompaction(t *testing.T) {
}
}
func TestUndecodableGatewayCompactionUsesBoundary(t *testing.T) {
func TestUndecodableGatewayCompactionReturnsRequestError(t *testing.T) {
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
}
expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":"g2a_compact_v1.invalid"}]}`), newGatewayCompactionCodec(cipher), "session-1")
body := []byte(`{"input":[{"type":"compaction","encrypted_content":"g2a_compact_v1.invalid"}]}`)
expanded, drifted, err := expandGatewayCompactionHistory(body, newGatewayCompactionCodec(cipher), "session-1")
var requestErr *responsesRequestError
if !errors.As(err, &requestErr) || requestErr.Code != "invalid_compaction_blob" || requestErr.Param != "input[0].encrypted_content" {
t.Fatalf("error = %#v", err)
}
if drifted != 0 || !bytes.Equal(expanded, body) {
t.Fatalf("expanded = %s, drifted = %d", expanded, drifted)
}
}
func TestForwardResponseRejectsUndecodableGatewayCompactionBeforeUpstream(t *testing.T) {
adapter, encrypted := newCompactionTestAdapter(t)
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
calls.Add(1)
return jsonHTTPResponse(request, http.StatusOK, `{}`), 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",
NormalizeBody: true,
Body: []byte(`{"model":"public","input":[{"type":"compaction","encrypted_content":"g2a_compact_v1.invalid"}]}`),
})
if err != nil {
t.Fatal(err)
}
if foreign != 1 || drifted != 0 || strings.Contains(string(expanded), "g2a_compact_v1.invalid") || !strings.Contains(string(expanded), "could not be decoded") {
t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, drifted)
defer response.Body.Close()
body, _ := io.ReadAll(response.Body)
if calls.Load() != 0 || response.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), `"code":"invalid_compaction_blob"`) || !strings.Contains(string(body), `"param":"input[0].encrypted_content"`) {
t.Fatalf("calls=%d status=%d body=%s", calls.Load(), response.StatusCode, body)
}
}
@@ -278,17 +304,55 @@ func TestPrepareGatewayCompactionSampleOmitsToolChoiceWithoutTools(t *testing.T)
}
}
func TestForeignCompactionNeverReachesBuildModelInput(t *testing.T) {
func TestUpstreamCompactionBlobIsForwarded(t *testing.T) {
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
}
expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAAABforeign-codex-replay"},{"role":"user","content":"continue"}]}`), newGatewayCompactionCodec(cipher), "session-1")
blob := "opaque/upstream+compact=blob"
body := []byte(`{"previous_response_id":"resp_compacted","input":[{"type":"compaction","encrypted_content":` + mustJSONString(blob) + `},{"role":"user","content":"continue"}]}`)
expanded, drifted, err := expandGatewayCompactionHistory(body, newGatewayCompactionCodec(cipher), "session-1")
if err != nil {
t.Fatal(err)
}
if foreign != 1 || drifted != 0 || strings.Contains(string(expanded), "gAAAAABforeign-codex-replay") || strings.Contains(string(expanded), `"type":"compaction"`) {
t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, drifted)
if drifted != 0 || !bytes.Equal(expanded, body) {
t.Fatalf("expanded = %s, drifted = %d", expanded, drifted)
}
}
func TestForwardResponseKeepsUpstreamCompactionBlob(t *testing.T) {
adapter, encrypted := newCompactionTestAdapter(t)
blob := "opaque/upstream+compact=blob"
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
data, readErr := io.ReadAll(request.Body)
if readErr != nil {
t.Fatal(readErr)
}
var forwarded struct {
PreviousResponseID string `json:"previous_response_id"`
Input []struct {
Type string `json:"type"`
ID string `json:"id"`
EncryptedContent string `json:"encrypted_content"`
} `json:"input"`
}
if json.Unmarshal(data, &forwarded) != nil || forwarded.PreviousResponseID != "resp_compacted" || len(forwarded.Input) != 2 || forwarded.Input[0].Type != "compaction" || forwarded.Input[0].ID != "cmp_upstream" || forwarded.Input[0].EncryptedContent != blob || strings.Contains(string(data), "could not be decoded") {
t.Fatalf("upstream compact blob was rewritten: %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",
NormalizeBody: true,
Body: []byte(`{"model":"public","previous_response_id":"resp_compacted","input":[{"type":"compaction","id":"cmp_upstream","encrypted_content":` + mustJSONString(blob) + `},{"role":"user","content":"continue"}]}`),
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK || response.Header.Get("X-Grok2API-Compatibility-Warnings") != "" {
t.Fatalf("status=%d warnings=%q", response.StatusCode, response.Header.Get("X-Grok2API-Compatibility-Warnings"))
}
}
@@ -13,11 +13,14 @@ import (
)
var reasoningDecodeFailureMarkers = [][]byte{
[]byte("could not decode the compaction blob"),
[]byte("could not decrypt the provided encrypted_content"),
[]byte("invalid_encrypted_content"),
}
var compactionBlobDecodeFailureMarkers = [][]byte{
[]byte("could not decode the compaction blob"),
}
type reasoningRecoveryOutcome struct {
encryptedContentDowngraded bool
sessionReset bool
@@ -107,6 +110,14 @@ func (a *Adapter) recoverReasoningDecodeFailure(
if truncated || !isReasoningDecodeFailure(errorBody) {
return originalCall, reasoningRecoveryOutcome{}, nil
}
// Build historically reused the compaction-decode wording for opaque
// reasoning and server-side session failures. Only treat that wording as a
// real compaction rejection when the rejected request actually carried a
// compaction input item. This preserves reasoning recovery without ever
// rewriting a client-held compact state.
if isCompactionBlobDecodeFailure(errorBody) && hasCompactionInputItem(body) {
return originalCall, reasoningRecoveryOutcome{}, nil
}
out := reasoningRecoveryOutcome{}
// 一旦上游明确拒绝 opaque reasoning,立即清理该账号/平面的服务端回放,
// 防止下次请求再次注入同一份已失效密文。成功响应会按正常 Capture 流程写回新状态。
@@ -265,8 +276,16 @@ func (a *Adapter) logReasoningRecovery(request provider.ResponseResourceRequest,
}
func isReasoningDecodeFailure(body []byte) bool {
return isCompactionBlobDecodeFailure(body) || containsDecodeFailureMarker(body, reasoningDecodeFailureMarkers)
}
func isCompactionBlobDecodeFailure(body []byte) bool {
return containsDecodeFailureMarker(body, compactionBlobDecodeFailureMarkers)
}
func containsDecodeFailureMarker(body []byte, markers [][]byte) bool {
lower := bytes.ToLower(body)
for _, marker := range reasoningDecodeFailureMarkers {
for _, marker := range markers {
if bytes.Contains(lower, marker) {
return true
}
@@ -274,11 +293,27 @@ func isReasoningDecodeFailure(body []byte) bool {
return false
}
// stripReasoningEncryptedContent removes undecodable opaque reasoning and
// compaction ciphertext so Grok Build does not fail on server-side decryption.
func hasCompactionInputItem(body []byte) bool {
var payload struct {
Input []struct {
Type string `json:"type"`
} `json:"input"`
}
if json.Unmarshal(body, &payload) != nil {
return false
}
for _, item := range payload.Input {
if strings.TrimSpace(item.Type) == "compaction" {
return true
}
}
return false
}
// stripReasoningEncryptedContent removes only undecodable opaque reasoning.
// Readable reasoning summaries are kept as portable assistant messages; empty
// encrypted-only reasoning items are dropped. Foreign compaction blobs become
// a boundary note because this gateway cannot decrypt them.
// encrypted-only reasoning items are dropped. Compaction items are client-held
// upstream state and must never be rewritten by reasoning recovery.
func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
var payload map[string]any
if json.Unmarshal(body, &payload) != nil {
@@ -296,8 +331,7 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
rebuilt = append(rebuilt, raw)
continue
}
switch stringField(item, "type") {
case "reasoning":
if stringField(item, "type") == "reasoning" {
encrypted, hasEncrypted := item["encrypted_content"].(string)
if !hasEncrypted || strings.TrimSpace(encrypted) == "" {
if portable, ok := portableReasoningSummaryMessage(item); ok {
@@ -312,16 +346,9 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
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."))
default:
rebuilt = append(rebuilt, raw)
continue
}
rebuilt = append(rebuilt, raw)
}
if !changed {
return body, false
@@ -47,8 +47,8 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T
t.Fatalf("readable reasoning text = %q", summaryText)
}
compaction := payload.Input[1]
if compaction["type"] != "message" || compaction["role"] != "developer" {
t.Fatalf("compaction boundary item = %#v", compaction)
if compaction["type"] != "compaction" || compaction["encrypted_content"] != "opaque-compaction" {
t.Fatalf("compaction item was rewritten: %#v", compaction)
}
if payload.Input[2]["encrypted_content"] != "message-value" {
t.Fatalf("non-reasoning encrypted content changed: %#v", payload.Input[2])
@@ -454,19 +454,20 @@ func TestRecoverReasoningDecodeFailurePreservesServerErrorAfterSessionReset(t *t
}
}
// TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob 覆盖 Claude Code
// 在超长上下文压缩后回放大体积 opaque 状态、且上游拒绝该状态的恢复路径。
func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *testing.T) {
// TestRecoverReasoningDecodeFailureWithMillionTokenScaleOpaqueReasoning keeps
// the legacy Build wording compatible with large reasoning replay payloads.
// The request has no compaction item, so the opaque reasoning remains eligible
// for same-account recovery even when Build calls it a compaction blob.
func TestRecoverReasoningDecodeFailureWithMillionTokenScaleOpaqueReasoning(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
// 按常用的约 4 字节/token 估算,4 MiB 的 opaque 状态覆盖约 100 万 token 的量级。
compactionBlob := strings.Repeat("x", 4<<20)
opaqueReasoning := strings.Repeat("x", 4<<20)
body, err := json.Marshal(map[string]any{
"model": "grok-4.5",
"input": []any{
map[string]any{
"type": "reasoning",
"summary": []any{},
"encrypted_content": compactionBlob,
"encrypted_content": opaqueReasoning,
},
map[string]any{"role": "user", "content": "压缩后继续执行"},
},
@@ -484,14 +485,14 @@ func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *tes
switch call {
case 1:
if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) {
t.Fatalf("初始 1M 级 compaction 请求不完整:size=%d", len(data))
t.Fatalf("初始 1M 级 reasoning 请求不完整:size=%d", len(data))
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
case 2:
if len(data) >= 4096 || strings.Contains(string(data), `"encrypted_content"`) || !strings.Contains(string(data), "压缩后继续执行") {
t.Fatalf("恢复请求仍携带 opaque 状态:size=%d", len(data))
t.Fatalf("恢复请求仍携带 opaque reasoning:size=%d", len(data))
}
return jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited after compaction recovery"}}`), nil
return jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited after reasoning recovery"}}`), nil
default:
t.Fatalf("unexpected call %d", call)
return nil, nil
@@ -512,11 +513,70 @@ func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *tes
defer response.Body.Close()
responseBody, _ := io.ReadAll(response.Body)
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
if calls.Load() != 2 || response.StatusCode != http.StatusTooManyRequests || !strings.Contains(string(responseBody), "rate limited after compaction recovery") || !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") {
if calls.Load() != 2 || response.StatusCode != http.StatusTooManyRequests || !strings.Contains(string(responseBody), "rate limited after reasoning recovery") || !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") {
t.Fatalf("calls=%d status=%d warnings=%q body=%s", calls.Load(), response.StatusCode, warnings, responseBody)
}
}
// TestCompactionBlobDecodeFailureIsReturnedToClient covers Claude Code
// replaying a large opaque compact state that Build rejects. That 400 is
// surfaced; recovery must not strip the blob and retry.
func TestCompactionBlobDecodeFailureIsReturnedToClient(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
compactionBlob := strings.Repeat("x", 4<<20)
body, err := json.Marshal(map[string]any{
"model": "grok-4.5",
"previous_response_id": "resp_compacted",
"input": []any{
map[string]any{
"type": "compaction",
"encrypted_content": compactionBlob,
},
map[string]any{"role": "user", "content": "压缩后继续执行"},
},
})
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
call := calls.Add(1)
data, readErr := io.ReadAll(request.Body)
if readErr != nil {
t.Fatal(readErr)
}
if call != 1 {
t.Fatalf("unexpected recovery retry %d", call)
}
if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) || !strings.Contains(string(data), `"previous_response_id":"resp_compacted"`) {
t.Fatalf("compact blob was not forwarded: size=%d", len(data))
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), 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: "million-token-session",
Body: body,
NormalizeBody: true,
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
responseBody, _ := io.ReadAll(response.Body)
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
if calls.Load() != 1 || response.StatusCode != http.StatusBadRequest || !strings.Contains(string(responseBody), "Could not decode the compaction blob") || strings.Contains(warnings, "reasoning_encrypted_content_downgraded") {
t.Fatalf("calls=%d status=%d warnings=%q body=%s", calls.Load(), response.StatusCode, warnings, responseBody)
}
if response.ReasoningRecoveryFailed || len(response.RecoveredAttempts) != 0 {
t.Fatalf("surfaced compaction 400 must remain the sole final attempt: %#v", response.RecoveredAttempts)
}
}
func TestRecoverReasoningDecodeFailureDoesNotResetStoredResponseChain(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
@@ -706,7 +766,7 @@ func TestRecoverReasoningDecodeFailureContinuesToSessionResetWhenStripRewords400
}
}
func TestRecoverReasoningDecodeFailureCompactionBlob(t *testing.T) {
func TestRecoverReasoningDecodeFailureKeepsLegacyCompactionMarkerWithoutCompactionInput(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
@@ -727,7 +787,7 @@ func TestRecoverReasoningDecodeFailureCompactionBlob(t *testing.T) {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected status 200, got %d", resp.StatusCode)
if calls.Load() != 2 || resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_session_reset") {
t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), resp.StatusCode, resp.Header.Get("X-Grok2API-Compatibility-Warnings"))
}
}