From 990bd7bea03e24951572f39cdd007e088108973c Mon Sep 17 00:00:00 2001 From: buddhism5080 Date: Sat, 29 Aug 2026 06:54:26 +0800 Subject: [PATCH] fix(cli): forward original compact blobs and surface decode 400s Client compaction items without the g2a_compact_v1 prefix are treated as upstream original state and sent to Build unchanged. Compact blob decode rejections are returned to the client instead of being recovered as opaque reasoning. Gateway-owned g2a blobs still expand locally. --- README.md | 2 +- .../provider/cli/responses_compaction.go | 20 ++++---- .../provider/cli/responses_compaction_test.go | 35 +++++++++++-- .../cli/responses_reasoning_recovery.go | 17 +++++-- .../cli/responses_reasoning_recovery_test.go | 50 ++++++++----------- 5 files changed, 78 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 616cd3c1..8ddbe06b 100644 --- a/README.md +++ b/README.md @@ -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. Other compaction blobs are forwarded as original upstream state; if Build rejects them, that error 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. diff --git a/backend/internal/infra/provider/cli/responses_compaction.go b/backend/internal/infra/provider/cli/responses_compaction.go index ed9adbcb..c5dda1e1 100644 --- a/backend/internal/infra/provider/cli/responses_compaction.go +++ b/backend/internal/infra/provider/cli/responses_compaction.go @@ -87,8 +87,10 @@ 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. +// 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. If Build +// rejects an original blob, that error is returned to the client. func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, session string) ([]byte, int, int, error) { var payload map[string]any if err := json.Unmarshal(body, &payload); err != nil { @@ -114,14 +116,12 @@ func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, changed = true 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.") + if !owned { + continue + } + items[index] = gatewayCompactionSummaryMessage(summary) + if sessionDrifted { + drifted++ } changed = true } diff --git a/backend/internal/infra/provider/cli/responses_compaction_test.go b/backend/internal/infra/provider/cli/responses_compaction_test.go index 4933802a..19826f6f 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_test.go +++ b/backend/internal/infra/provider/cli/responses_compaction_test.go @@ -278,20 +278,49 @@ 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" + expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`},{"role":"user","content":"continue"}]}`), 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"`) { + if foreign != 0 || drifted != 0 || !strings.Contains(string(expanded), blob) || !strings.Contains(string(expanded), `"type":"compaction"`) { t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, 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) + } + if !strings.Contains(string(data), blob) || !strings.Contains(string(data), `"type":"compaction"`) || 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","input":[{"type":"compaction","encrypted_content":` + mustJSONString(blob) + `},{"role":"user","content":"continue"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK || strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "foreign_compaction_omitted") { + t.Fatalf("status=%d warnings=%q", response.StatusCode, response.Header.Get("X-Grok2API-Compatibility-Warnings")) + } +} + func TestRemoteCompactionTriggerMustBeTerminal(t *testing.T) { _, _, err := normalizeResponsesRequest([]byte(`{"model":"public","input":[{"type":"compaction_trigger"},{"role":"user","content":"late item"}]}`), "grok-4.5") var requestErr *responsesRequestError diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go index e0527dce..96b8646e 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go @@ -13,10 +13,13 @@ import ( ) var reasoningDecodeFailureMarkers = [][]byte{ - []byte("could not decode the compaction blob"), []byte("could not decrypt the provided encrypted_content"), } +var compactionBlobDecodeFailureMarkers = [][]byte{ + []byte("could not decode the compaction blob"), +} + type reasoningRecoveryOutcome struct { encryptedContentDowngraded bool sessionReset bool @@ -71,7 +74,7 @@ func (a *Adapter) recoverReasoningDecodeFailure( return cloneBufferedResponse(response, errorBody, truncated), requestURL, reasoningRecoveryOutcome{} } original := cloneBufferedResponse(response, errorBody, truncated) - if truncated || !isReasoningDecodeFailure(errorBody) { + if truncated || isCompactionBlobDecodeFailure(errorBody) || !isReasoningDecodeFailure(errorBody) { return original, requestURL, reasoningRecoveryOutcome{} } // 一旦上游明确拒绝 opaque reasoning,立即清理该账号/平面的服务端回放, @@ -230,8 +233,16 @@ func (a *Adapter) logReasoningRecovery(request provider.ResponseResourceRequest, } func isReasoningDecodeFailure(body []byte) bool { + return 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 } diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go index d5580c97..ec2f2c8e 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go @@ -139,7 +139,7 @@ func TestRecoverReasoningDecodeFailureStaysOnXAIFallbackPlane(t *testing.T) { if request.URL.Host != "xai.test" { t.Fatalf("fallback host = %q", request.URL.Host) } - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil case 3: data, _ := io.ReadAll(request.Body) if request.URL.Host != "xai.test" || strings.Contains(string(data), `"type":"reasoning"`) { @@ -179,7 +179,7 @@ func TestRecoverReasoningDecodeFailureResetsSessionWithoutOpaqueInput(t *testing if request.Header.Get("x-grok-session-id") == "" || !strings.Contains(string(data), `"prompt_cache_key":"session-1"`) { t.Fatalf("initial session request headers=%#v body=%s", request.Header, data) } - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil case 2: if request.Header.Get("x-grok-session-id") != "" || request.Header.Get("x-grok-conv-id") != "" || strings.Contains(string(data), `"prompt_cache_key"`) { t.Fatalf("stateless recovery headers=%#v body=%s", request.Header, data) @@ -228,7 +228,7 @@ func TestRecoverReasoningDecodeFailureEscalatesFromOpaqueStripToSessionReset(t * default: t.Fatalf("unexpected call %d", call) } - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil }) response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, @@ -251,7 +251,7 @@ func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterOpaqueStrip(t *test adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { switch calls.Add(1) { case 1: - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil case 2: data, _ := io.ReadAll(request.Body) if strings.Contains(string(data), `"encrypted_content"`) { @@ -306,7 +306,7 @@ func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterSessionReset(t *tes t.Fatalf("unexpected call %d", call) return nil, nil } - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil }) response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ @@ -328,18 +328,17 @@ func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterSessionReset(t *tes } } -// TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob 覆盖 Claude Code -// 在超长上下文压缩后回放大体积 opaque 状态、且上游拒绝该状态的恢复路径。 -func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *testing.T) { +// 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) - // 按常用的约 4 字节/token 估算,4 MiB 的 opaque 状态覆盖约 100 万 token 的量级。 compactionBlob := 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{}, + "type": "compaction", "encrypted_content": compactionBlob, }, map[string]any{"role": "user", "content": "压缩后继续执行"}, @@ -355,21 +354,13 @@ func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *tes if readErr != nil { t.Fatal(readErr) } - switch call { - case 1: - if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) { - t.Fatalf("初始 1M 级 compaction 请求不完整: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)) - } - return jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited after compaction recovery"}}`), nil - default: - t.Fatalf("unexpected call %d", call) - return nil, nil + if call != 1 { + t.Fatalf("unexpected recovery retry %d", call) } + if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) { + 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{ @@ -379,6 +370,7 @@ func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *tes Model: "grok-4.5", PromptCacheKey: "million-token-session", Body: body, + NormalizeBody: true, }) if err != nil { t.Fatal(err) @@ -386,7 +378,7 @@ 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() != 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) } } @@ -396,7 +388,7 @@ func TestRecoverReasoningDecodeFailureDoesNotResetStoredResponseChain(t *testing var calls atomic.Int32 adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { calls.Add(1) - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil }) response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, @@ -417,7 +409,7 @@ func TestRecoverReasoningDecodeFailurePreservesOriginalWhenRetryFails(t *testing var calls atomic.Int32 adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { if calls.Add(1) == 1 { - return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil } return jsonHTTPResponse(request, http.StatusServiceUnavailable, `{"error":"temporary failure"}`), nil }) @@ -431,7 +423,7 @@ func TestRecoverReasoningDecodeFailurePreservesOriginalWhenRetryFails(t *testing } defer response.Body.Close() data, _ := io.ReadAll(response.Body) - if calls.Load() != 2 || response.StatusCode != http.StatusBadRequest || !strings.Contains(string(data), "Could not decode") || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") { + if calls.Load() != 2 || response.StatusCode != http.StatusBadRequest || !strings.Contains(string(data), "Could not decrypt") || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") { t.Fatalf("calls=%d status=%d headers=%#v body=%s", calls.Load(), response.StatusCode, response.Header, data) } }