From e3420857e903363af4867b0f8f8dbe1779d83c31 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Wed, 19 Aug 2026 01:57:40 +0800 Subject: [PATCH 1/2] fix: skip quality hold for Grok TUI compaction prompts TUI context compaction posts a normal /v1/responses turn whose last user item is the grok-build summary prompt, not compaction_trigger. Quality hold treated that as missing-thinking, withheld the stream, and fail-closed after six long attempts. Detect the prompt on the last input/message item, tag the request as compaction, and skip the hold without rewriting the body into a Codex remote-v2 blob. --- .../application/gateway/quality_retry.go | 6 ++ .../application/gateway/quality_retry_test.go | 8 ++ .../gateway/responses_compaction.go | 78 +++++++++++++++++-- .../gateway/responses_compaction_test.go | 6 ++ 4 files changed, 91 insertions(+), 7 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index df99047a..1dfda264 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -203,6 +203,12 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn default: return false } + // TUI compaction is a normal /v1/responses body (no compaction_trigger). + // CreateResponse retags it to OperationCompaction; also skip here so a + // missed tag cannot withhold a 100s+ summary as missing-thinking. + if isResponsesCompactionRequest(input.Body) { + return false + } if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole { return false } diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 409569d7..fb836a7a 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -495,6 +495,14 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { if shouldHoldQualityStream(input, nil, route, audit.OperationImage, cfg) { t.Fatal("image must not hold") } + if shouldHoldQualityStream(input, nil, route, audit.OperationCompaction, cfg) { + t.Fatal("codex compaction operation must not hold") + } + tui := input + tui.Body = []byte(`{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`) + if shouldHoldQualityStream(tui, nil, route, audit.OperationResponses, cfg) { + t.Fatal("tui compaction prompt must not hold even when tagged responses") + } for _, test := range []struct { name string body string diff --git a/backend/internal/application/gateway/responses_compaction.go b/backend/internal/application/gateway/responses_compaction.go index 44e24178..6db87708 100644 --- a/backend/internal/application/gateway/responses_compaction.go +++ b/backend/internal/application/gateway/responses_compaction.go @@ -5,22 +5,86 @@ import ( "strings" ) -// isResponsesCompactionRequest detects Codex remote compaction v2 without -// retaining or logging the request body. The Provider adapter remains the -// authority for validating that the trigger appears exactly once and last. +// Distinctive line from grok-build full_replace_summary_prompt.txt and the +// Grok TUI compaction request. Codex remote-v2 uses compaction_trigger +// instead; the TUI appends this prompt as a normal last user item. +const clientCompactionPromptMarker = "it is a system-generated compaction prompt, not a real user message" + +// isResponsesCompactionRequest detects a context-compaction turn without +// retaining the request body. Codex remote compaction v2 sends +// compaction_trigger; Grok TUI sends the canonical summary prompt as the +// last input/message item. The Provider adapter still requires the trigger +// before it rewrites the body into an encrypted compaction blob. func isResponsesCompactionRequest(body []byte) bool { var payload struct { - Input []struct { - Type string `json:"type"` - } `json:"input"` + Input []json.RawMessage `json:"input"` + Messages []json.RawMessage `json:"messages"` } if json.Unmarshal(body, &payload) != nil { return false } - for _, item := range payload.Input { + if hasCompactionTrigger(payload.Input) { + return true + } + return lastItemLooksLikeCompactionPrompt(payload.Input) || lastItemLooksLikeCompactionPrompt(payload.Messages) +} + +func hasCompactionTrigger(items []json.RawMessage) bool { + for _, raw := range items { + var item struct { + Type string `json:"type"` + } + if json.Unmarshal(raw, &item) != nil { + continue + } if strings.EqualFold(strings.TrimSpace(item.Type), "compaction_trigger") { return true } } return false } + +func lastItemLooksLikeCompactionPrompt(items []json.RawMessage) bool { + if len(items) == 0 { + return false + } + return looksLikeCompactionPrompt(extractInputItemText(items[len(items)-1])) +} + +func looksLikeCompactionPrompt(text string) bool { + return strings.Contains(text, clientCompactionPromptMarker) +} + +func extractInputItemText(raw json.RawMessage) string { + var item struct { + Content json.RawMessage `json:"content"` + } + if json.Unmarshal(raw, &item) != nil { + return extractContentText(raw) + } + if len(item.Content) > 0 { + return extractContentText(item.Content) + } + return extractContentText(raw) +} + +func extractContentText(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var text string + if json.Unmarshal(raw, &text) == nil { + return text + } + var parts []struct { + Text string `json:"text"` + } + if json.Unmarshal(raw, &parts) == nil { + var builder strings.Builder + for _, part := range parts { + builder.WriteString(part.Text) + } + return builder.String() + } + return "" +} diff --git a/backend/internal/application/gateway/responses_compaction_test.go b/backend/internal/application/gateway/responses_compaction_test.go index b7d60f63..37734406 100644 --- a/backend/internal/application/gateway/responses_compaction_test.go +++ b/backend/internal/application/gateway/responses_compaction_test.go @@ -2,6 +2,8 @@ package gateway import "testing" +const tuiCompactionPrompt = "Your task is to produce a faithful, concise summary of the conversation so far. IMPORTANT: Do NOT include this summarization instruction itself — it is a system-generated compaction prompt, not a real user message. Output the final summary inside a single block." + func TestIsResponsesCompactionRequest(t *testing.T) { tests := []struct { name string @@ -10,6 +12,10 @@ func TestIsResponsesCompactionRequest(t *testing.T) { }{ {name: "remote v2", body: `{"input":[{"role":"user","content":"continue"},{"type":"compaction_trigger"}]}`, want: true}, {name: "not terminal", body: `{"input":[{"type":"compaction_trigger"},{"role":"user","content":"continue"}]}`, want: true}, + {name: "tui last user string", body: `{"input":[{"role":"user","content":"continue"},{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`, want: true}, + {name: "tui last user parts", body: `{"input":[{"role":"user","content":[{"type":"input_text","text":"` + tuiCompactionPrompt + `"}]}]}`, want: true}, + {name: "tui chat messages", body: `{"messages":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`, want: true}, + {name: "prompt only in history", body: `{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"},{"role":"user","content":"continue the task"}]}`}, {name: "normal responses", body: `{"input":[{"role":"user","content":"continue"}]}`}, {name: "string input", body: `{"input":"continue"}`}, {name: "invalid json", body: `{`}, From c0b870cbaed0fb910d291f713ec837459e387785 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 19 Aug 2026 13:48:23 +0800 Subject: [PATCH 2/2] fix: preserve Responses routing for Grok TUI compaction --- .../application/gateway/quality_retry.go | 6 +-- .../application/gateway/quality_retry_test.go | 5 +++ .../gateway/responses_compaction.go | 43 +++++++++++-------- .../gateway/responses_compaction_test.go | 30 +++++++------ .../internal/application/gateway/service.go | 20 ++++++++- .../application/gateway/service_test.go | 39 +++++++++++++++++ 6 files changed, 109 insertions(+), 34 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 1dfda264..b0f19014 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -195,7 +195,7 @@ func CommitQualityHold(verdict QualityVerdict, qualityAttempt, maxAttempts int, } func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwnership, route modeldomain.Route, operation audit.Operation, cfg QualityRetryRuntime) bool { - if !cfg.Enabled || !input.Streaming || input.ForcedEgressNodeID != 0 || ownership != nil { + if !cfg.Enabled || !input.Streaming || input.ForcedEgressNodeID != 0 || ownership != nil || input.skipQualityHold { return false } switch operation { @@ -204,8 +204,8 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn return false } // TUI compaction is a normal /v1/responses body (no compaction_trigger). - // CreateResponse retags it to OperationCompaction; also skip here so a - // missed tag cannot withhold a 100s+ summary as missing-thinking. + // Keep this defensive body check in addition to skipQualityHold so a caller + // that bypasses CreateResponse cannot withhold a 100s+ summary as missing-thinking. if isResponsesCompactionRequest(input.Body) { return false } diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index fb836a7a..e51b5785 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -498,6 +498,11 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { if shouldHoldQualityStream(input, nil, route, audit.OperationCompaction, cfg) { t.Fatal("codex compaction operation must not hold") } + classified := input + classified.skipQualityHold = true + if shouldHoldQualityStream(classified, nil, route, audit.OperationResponses, cfg) { + t.Fatal("gateway-classified compaction must not hold") + } tui := input tui.Body = []byte(`{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`) if shouldHoldQualityStream(tui, nil, route, audit.OperationResponses, cfg) { diff --git a/backend/internal/application/gateway/responses_compaction.go b/backend/internal/application/gateway/responses_compaction.go index 6db87708..e4679d46 100644 --- a/backend/internal/application/gateway/responses_compaction.go +++ b/backend/internal/application/gateway/responses_compaction.go @@ -10,23 +10,38 @@ import ( // instead; the TUI appends this prompt as a normal last user item. const clientCompactionPromptMarker = "it is a system-generated compaction prompt, not a real user message" +type responsesCompactionKind uint8 + +const ( + responsesCompactionNone responsesCompactionKind = iota + responsesCompactionTrigger + responsesCompactionTUI +) + // isResponsesCompactionRequest detects a context-compaction turn without // retaining the request body. Codex remote compaction v2 sends // compaction_trigger; Grok TUI sends the canonical summary prompt as the // last input/message item. The Provider adapter still requires the trigger // before it rewrites the body into an encrypted compaction blob. func isResponsesCompactionRequest(body []byte) bool { + return classifyResponsesCompactionRequest(body) != responsesCompactionNone +} + +func classifyResponsesCompactionRequest(body []byte) responsesCompactionKind { var payload struct { Input []json.RawMessage `json:"input"` Messages []json.RawMessage `json:"messages"` } if json.Unmarshal(body, &payload) != nil { - return false + return responsesCompactionNone } if hasCompactionTrigger(payload.Input) { - return true + return responsesCompactionTrigger } - return lastItemLooksLikeCompactionPrompt(payload.Input) || lastItemLooksLikeCompactionPrompt(payload.Messages) + if lastItemLooksLikeCompactionPrompt(payload.Input) || lastItemLooksLikeCompactionPrompt(payload.Messages) { + return responsesCompactionTUI + } + return responsesCompactionNone } func hasCompactionTrigger(items []json.RawMessage) bool { @@ -48,26 +63,20 @@ func lastItemLooksLikeCompactionPrompt(items []json.RawMessage) bool { if len(items) == 0 { return false } - return looksLikeCompactionPrompt(extractInputItemText(items[len(items)-1])) + var item struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` + } + if json.Unmarshal(items[len(items)-1], &item) != nil || !strings.EqualFold(strings.TrimSpace(item.Role), "user") { + return false + } + return looksLikeCompactionPrompt(extractContentText(item.Content)) } func looksLikeCompactionPrompt(text string) bool { return strings.Contains(text, clientCompactionPromptMarker) } -func extractInputItemText(raw json.RawMessage) string { - var item struct { - Content json.RawMessage `json:"content"` - } - if json.Unmarshal(raw, &item) != nil { - return extractContentText(raw) - } - if len(item.Content) > 0 { - return extractContentText(item.Content) - } - return extractContentText(raw) -} - func extractContentText(raw json.RawMessage) string { if len(raw) == 0 { return "" diff --git a/backend/internal/application/gateway/responses_compaction_test.go b/backend/internal/application/gateway/responses_compaction_test.go index 37734406..7f8bfc18 100644 --- a/backend/internal/application/gateway/responses_compaction_test.go +++ b/backend/internal/application/gateway/responses_compaction_test.go @@ -8,22 +8,28 @@ func TestIsResponsesCompactionRequest(t *testing.T) { tests := []struct { name string body string - want bool + want responsesCompactionKind }{ - {name: "remote v2", body: `{"input":[{"role":"user","content":"continue"},{"type":"compaction_trigger"}]}`, want: true}, - {name: "not terminal", body: `{"input":[{"type":"compaction_trigger"},{"role":"user","content":"continue"}]}`, want: true}, - {name: "tui last user string", body: `{"input":[{"role":"user","content":"continue"},{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`, want: true}, - {name: "tui last user parts", body: `{"input":[{"role":"user","content":[{"type":"input_text","text":"` + tuiCompactionPrompt + `"}]}]}`, want: true}, - {name: "tui chat messages", body: `{"messages":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`, want: true}, - {name: "prompt only in history", body: `{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"},{"role":"user","content":"continue the task"}]}`}, - {name: "normal responses", body: `{"input":[{"role":"user","content":"continue"}]}`}, - {name: "string input", body: `{"input":"continue"}`}, - {name: "invalid json", body: `{`}, + {name: "remote v2", body: `{"input":[{"role":"user","content":"continue"},{"type":"compaction_trigger"}]}`, want: responsesCompactionTrigger}, + {name: "not terminal", body: `{"input":[{"type":"compaction_trigger"},{"role":"user","content":"continue"}]}`, want: responsesCompactionTrigger}, + {name: "tui last user string", body: `{"input":[{"role":"user","content":"continue"},{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`, want: responsesCompactionTUI}, + {name: "tui last user parts", body: `{"input":[{"role":"user","content":[{"type":"input_text","text":"` + tuiCompactionPrompt + `"}]}]}`, want: responsesCompactionTUI}, + {name: "tui chat messages", body: `{"messages":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`, want: responsesCompactionTUI}, + {name: "prompt only in history", body: `{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"},{"role":"user","content":"continue the task"}]}`, want: responsesCompactionNone}, + {name: "assistant prompt", body: `{"input":[{"role":"assistant","content":"` + tuiCompactionPrompt + `"}]}`, want: responsesCompactionNone}, + {name: "system prompt", body: `{"messages":[{"role":"system","content":"` + tuiCompactionPrompt + `"}]}`, want: responsesCompactionNone}, + {name: "missing role", body: `{"input":[{"content":"` + tuiCompactionPrompt + `"}]}`, want: responsesCompactionNone}, + {name: "normal responses", body: `{"input":[{"role":"user","content":"continue"}]}`, want: responsesCompactionNone}, + {name: "string input", body: `{"input":"continue"}`, want: responsesCompactionNone}, + {name: "invalid json", body: `{`, want: responsesCompactionNone}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - if got := isResponsesCompactionRequest([]byte(test.body)); got != test.want { - t.Fatalf("isResponsesCompactionRequest() = %t, want %t", got, test.want) + if got := classifyResponsesCompactionRequest([]byte(test.body)); got != test.want { + t.Fatalf("classifyResponsesCompactionRequest() = %d, want %d", got, test.want) + } + if got := isResponsesCompactionRequest([]byte(test.body)); got != (test.want != responsesCompactionNone) { + t.Fatalf("isResponsesCompactionRequest() = %t, want %t", got, test.want != responsesCompactionNone) } }) } diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 666bb7bd..5f1da2e7 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -107,6 +107,11 @@ type Input struct { // GrokTurnIndex forwards only the turn supplied by a real Grok Shell client; the server never infers or increments it. GrokTurnIndex string Operation audit.Operation + // auditOperation may classify a normal protocol request differently for + // operator visibility without changing routing or Provider semantics. + auditOperation audit.Operation + // skipQualityHold is set only by trusted gateway-side request classifiers. + skipQualityHold bool // ForcedEgressNodeID is an internal-only administrator probe constraint. // Public inference handlers never populate it. ForcedEgressNodeID uint64 @@ -487,8 +492,15 @@ func (s *Service) checkLedgerReady() error { func (s *Service) CreateResponse(ctx context.Context, input Input) (*Result, error) { input.Operation = audit.OperationResponses - if isResponsesCompactionRequest(input.Body) { + switch classifyResponsesCompactionRequest(input.Body) { + case responsesCompactionTrigger: input.Operation = audit.OperationCompaction + case responsesCompactionTUI: + // Grok TUI compaction is still a normal Responses request. Keep its + // routing, Provider normalization, and stored-response behavior intact; + // only its audit classification and quality-hold policy differ. + input.auditOperation = audit.OperationCompaction + input.skipQualityHold = true } return s.createResponseAt(ctx, input, "/responses") } @@ -821,6 +833,10 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string if operation == "" { operation = audit.OperationResponses } + auditOperation := operation + if input.auditOperation != "" { + auditOperation = input.auditOperation + } routes, aliasEffort, err := s.resolvePublicModelRoutes(ctx, input.PublicModel, input.ClientKey.AllowModelAliases) if err != nil { return nil, ErrModelNotFound @@ -918,7 +934,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string auditBase := audit.Record{ EventID: eventID, RequestID: input.RequestID, ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name, ModelRouteID: route.ID, ModelPublicID: publicModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), - Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: input.Streaming, + Provider: string(route.Provider), Operation: auditOperation, UsageSource: audit.UsageSourceNone, Streaming: input.Streaming, MediaInputImages: mediaSummary.InputImages, } if errors.Is(routeErr, clientkeyapp.ErrModelNotAllowed) { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index f161c727..31f17e63 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -272,6 +272,42 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("compaction response ownership err = %v", err) } + // Grok TUI compaction is a normal Responses request on the wire. It skips + // the quality hold and is labeled compaction only in the audit record, so + // Provider routing and stored-response ownership must remain intact. + service.UpdateQualityRetry(QualityRetryRuntime{ + Enabled: true, MaxAttempts: 2, MinOutputTokens: 32, + OnExhausted: qualityRetryFailClosed, HoldTimeout: time.Second, + }) + adapter.resetAttempts() + tuiCompacted, err := service.CreateResponse(ctx, Input{ + RequestID: "req-tui-compact", ClientKey: clientKey, PublicModel: "grok-test", PromptCacheSeed: "tui-session", + Body: []byte(`{"model":"grok-test","stream":true,"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`), Streaming: true, + }) + if err != nil { + t.Fatal(err) + } + tuiBody, err := io.ReadAll(tuiCompacted.Body) + if err != nil { + t.Fatal(err) + } + if string(tuiBody) != "ok" { + t.Fatalf("TUI compaction body = %q", tuiBody) + } + tuiCompacted.MarkFirstToken() + tuiCompacted.Finalize(Usage{}, "resp-tui-compact", "") + _ = tuiCompacted.Body.Close() + if len(adapter.attempts) != 1 || adapter.lastOperation != string(audit.OperationResponses) { + t.Fatalf("TUI compaction attempts = %#v, Provider operation = %q", adapter.attempts, adapter.lastOperation) + } + logs, total, err = auditRepo.List(ctx, 0, 10) + if err != nil || total != 3 || logs[0].Operation != audit.OperationCompaction { + t.Fatalf("TUI compaction audit = %#v, total=%d, err=%v", logs, total, err) + } + if ownership, err := responseRepo.Get(ctx, "resp-tui-compact", clientKey.ID, time.Now().UTC()); err != nil || ownership.AccountID != second.ID { + t.Fatalf("TUI compaction ownership = %#v, err=%v", ownership, err) + } + adapter.resetAttempts() continued, err := service.CreateResponse(ctx, Input{RequestID: "req-2", ClientKey: clientKey, PublicModel: "grok-test", PreviousResponseID: "resp-test", Body: []byte(`{"model":"grok-test","previous_response_id":"resp-test"}`)}) if err != nil { @@ -2598,6 +2634,7 @@ type failoverAdapter struct { lastPromptCacheKey string lastReasoningReplayKey string lastGrokTurnIndex string + lastOperation string reasoningEffort string forwardedModels []string resourceStatus int @@ -4160,6 +4197,7 @@ func (a *failoverAdapter) ForwardResponse(_ context.Context, request provider.Re a.lastPromptCacheKey = request.PromptCacheKey a.lastReasoningReplayKey = request.ReasoningReplayKey a.lastGrokTurnIndex = request.GrokTurnIndex + a.lastOperation = request.Operation resourceStatus := a.resourceStatus transportErr := a.transportErrorIDs[request.Credential.ID] a.mu.Unlock() @@ -4200,6 +4238,7 @@ func (a *failoverAdapter) resetAttempts() { a.lastPromptCacheKey = "" a.lastReasoningReplayKey = "" a.lastGrokTurnIndex = "" + a.lastOperation = "" } func (a *failoverAdapter) ForwardedModels() []string {