Merge pull request #967 from lij768423-svg/feat/skip-tui-compaction-hold

fix: skip quality hold for Grok TUI compaction prompts
This commit is contained in:
Chenyme authored and GitHub committed 2026-08-19 13:58:35 +08:00
commit e7f6137dc0
6 files changed
+109 -34

No files matched your search

@@ -253,7 +253,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 {
@@ -262,8 +262,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
}
@@ -542,6 +542,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) {
@@ -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 ""
@@ -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)
}
})
}
@@ -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
@@ -492,8 +497,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")
}
@@ -826,6 +838,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
@@ -923,7 +939,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) {
@@ -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 {
@@ -2602,6 +2638,7 @@ type failoverAdapter struct {
lastPromptCacheKey string
lastReasoningReplayKey string
lastGrokTurnIndex string
lastOperation string
reasoningEffort string
forwardedModels []string
resourceStatus int
@@ -4164,6 +4201,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()
@@ -4204,6 +4242,7 @@ func (a *failoverAdapter) resetAttempts() {
a.lastPromptCacheKey = ""
a.lastReasoningReplayKey = ""
a.lastGrokTurnIndex = ""
a.lastOperation = ""
}
func (a *failoverAdapter) ForwardedModels() []string {