mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
Merge branch 'main' into pr/1022
# Conflicts: # backend/internal/infra/provider/cli/responses_reasoning_recovery.go # backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go
This commit is contained in:
commit
b0ea8efdaa
24 files changed
+1493
-337
No files matched your search
@@ -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 `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 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.
|
||||
|
||||
@@ -369,8 +369,9 @@ qualityGuard:
|
||||
enabled: true
|
||||
model: "grok-4.6"
|
||||
# Withhold thinking-model streams that have no streamed reasoning.
|
||||
# Observe for up to 30s. An open stream with a reasoning start and visible
|
||||
# output is released at the deadline; empty/terminal failures still retry.
|
||||
# Observe for up to 30s. A stub plus enough visible output at the deadline
|
||||
# is withheld; empty stub-only streams keep waiting. Floor-met dumps that
|
||||
# flush a short greeting in under 1s are also withheld.
|
||||
requestRetry:
|
||||
enabled: true
|
||||
maxAttempts: 6
|
||||
@@ -381,7 +382,7 @@ qualityGuard:
|
||||
idleAccountCooldown: 15m
|
||||
```
|
||||
|
||||
`requestRetry` runs on the gateway request path and is independent of the sidecar. The example enables it. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; another account is tried. If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. Image, video, stored-response, and ForcedEgress probe requests are unchanged. Grok TUI tool turns stay held so 0-thinking dumps cannot skip the gate.
|
||||
`requestRetry` runs on the gateway request path and is independent of the sidecar. `config.example.yaml` keeps `enabled: false`; set it true to intercept. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; replay-safe stateless requests may try another account. TUI follow-ups (`previous_response_id`) and hosted-tool turns are still held for classification, but a quality withhold never replays account-bound state or side-effecting tools across accounts; `onExhausted` returns `503 quality_degraded` or releases that held body. Context compaction, image, video, and ForcedEgress probe requests are unchanged.
|
||||
|
||||
```bash
|
||||
docker compose --profile quality-guard up -d --build
|
||||
|
||||
+4
-4
@@ -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 语义分开报告未缓存输入和缓存读取。审计保留输入总量与缓存部分,用于计费对账。
|
||||
|
||||
@@ -365,8 +365,8 @@ qualityGuard:
|
||||
enabled: true
|
||||
model: "grok-4.6"
|
||||
# 思考模型缺流式 reasoning 时先扣住响应,换号再打,不把降智正文发给用户。
|
||||
# 最多观察 30 秒;已有 reasoning 起始信号和可见输出的进行中流会在超时后放行,
|
||||
# 空流和终态仍无 thinking 的响应继续换号。
|
||||
# 最多观察 30 秒;stub 加上足够可见输出在超时后扣住(TUI 30s 后的短问候),
|
||||
# 空 stub 继续等。floor 已达标但 1 秒内吐短回复的也扣。
|
||||
requestRetry:
|
||||
enabled: true
|
||||
maxAttempts: 6
|
||||
@@ -377,7 +377,7 @@ qualityGuard:
|
||||
idleAccountCooldown: 15m
|
||||
```
|
||||
|
||||
`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。示例配置默认开启。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试;全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。不处理图/视频、stored response 钉账号和 ForcedEgress 探针。Grok TUI 带 tools 的回合仍会 hold,避免 0-thinking 降智流跳过闸门。
|
||||
`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。`config.example.yaml` 里 `enabled` 仍为 false,打开后才拦截。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**;只有可安全重放的无状态请求才会排除账号重试。TUI 续聊(`previous_response_id`)和 hosted tools 仍会进入 hold 检测,但质量拦截不会把账号绑定状态或有副作用的工具跨账号重放,最终按 `onExhausted` 返回 `503 quality_degraded` 或放出当前响应。上下文压缩、图片、视频和 ForcedEgress 探针不受影响。
|
||||
|
||||
```bash
|
||||
docker compose --profile quality-guard up -d --build
|
||||
|
||||
@@ -491,13 +491,15 @@ func accountAutoCleanConfig(value config.AccountsConfig) accountapp.AutoCleanCon
|
||||
|
||||
func qualityRetryRuntime(value config.QualityGuardRequestRetryConfig) gateway.QualityRetryRuntime {
|
||||
return gateway.QualityRetryRuntime{
|
||||
Enabled: value.Enabled,
|
||||
MaxAttempts: value.MaxAttempts,
|
||||
HoldTimeout: value.HoldTimeout.Value(),
|
||||
MinOutputTokens: int64(value.MinOutputTokens),
|
||||
OnExhausted: value.OnExhausted,
|
||||
AccountCooldown: value.AccountCooldown.Value(),
|
||||
IdleAccountCooldown: value.IdleAccountCooldown.Value(),
|
||||
Enabled: value.Enabled,
|
||||
MaxAttempts: value.MaxAttempts,
|
||||
HoldTimeout: value.HoldTimeout.Value(),
|
||||
MinOutputTokens: int64(value.MinOutputTokens),
|
||||
OnExhausted: value.OnExhausted,
|
||||
AccountCooldown: value.AccountCooldown.Value(),
|
||||
IdleAccountCooldown: value.IdleAccountCooldown.Value(),
|
||||
MinEncryptedBytes: value.MinEncryptedBytes,
|
||||
EncryptedBytesPerReasoningToken: value.EncryptedBytesPerReasoningToken,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -171,6 +171,40 @@ func (r *failureAttemptRecorder) captureStreamFailure(credential accountdomain.C
|
||||
})
|
||||
}
|
||||
|
||||
func (r *failureAttemptRecorder) hasStreamFailureFor(accountID uint64) bool {
|
||||
for _, attempt := range r.attempts {
|
||||
if attempt.Stage != "response_stream" || attempt.AccountID == nil || *attempt.AccountID != accountID {
|
||||
continue
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ensureStreamFailureAttempt 补记已完成 2xx 响应头握手、但随后失败的流式尝试。
|
||||
// 既有 4xx 或传输失败记录不能屏蔽该尝试;同一账号已有 response_stream 时不重复追加。
|
||||
func (r *failureAttemptRecorder) ensureStreamFailureAttempt(credential accountdomain.Credential, startedAt time.Time, response *provider.Response, errorCode string) {
|
||||
if response == nil || response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices || r.hasStreamFailureFor(credential.ID) {
|
||||
return
|
||||
}
|
||||
statusCode := response.StatusCode
|
||||
r.append(audit.Attempt{
|
||||
Source: audit.AttemptSourceUpstreamHTTP,
|
||||
Stage: "response_stream",
|
||||
AccountID: auditAccountID(credential.ID),
|
||||
AccountName: credential.Name,
|
||||
Method: r.method,
|
||||
RequestPath: r.path,
|
||||
UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL),
|
||||
StartedAt: startedAt.UTC(),
|
||||
DurationMS: time.Since(startedAt).Milliseconds(),
|
||||
UpstreamStatusCode: &statusCode,
|
||||
UpstreamStatus: response.Status,
|
||||
ResponseHeaders: sanitizeDiagnosticHeaders(response.Header),
|
||||
TransportError: errorCode,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *failureAttemptRecorder) captureQualityDegraded(credential accountdomain.Credential, startedAt time.Time) {
|
||||
status := http.StatusOK
|
||||
r.append(audit.Attempt{
|
||||
|
||||
@@ -95,6 +95,45 @@ func TestFailureAttemptRecorderCapturesStreamFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureStreamFailureAttemptKeepsPrior429AndSkipsDuplicate(t *testing.T) {
|
||||
recorder := newFailureAttemptRecorder(http.MethodPost, "/responses")
|
||||
first := account.Credential{ID: 11, Name: "retry-a"}
|
||||
second := account.Credential{ID: 12, Name: "retry-b"}
|
||||
exhausted := &provider.Response{StatusCode: http.StatusTooManyRequests, Status: "Too Many Requests", Body: io.NopCloser(strings.NewReader(`{"code":"subscription:free-usage-exhausted"}`))}
|
||||
if err := recorder.captureResponse(first, time.Now(), exhausted, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream := &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"text/event-stream"}}, UpstreamURL: "https://cli-chat-proxy.grok.com/v1/responses"}
|
||||
recorder.ensureStreamFailureAttempt(second, time.Now().Add(-time.Second), stream, "upstream_stream_interrupted")
|
||||
stored := recorder.snapshot()
|
||||
if len(stored) != 2 || stored[0].Stage != "upstream_response" || stored[1].Stage != "response_stream" {
|
||||
t.Fatalf("attempts = %#v", stored)
|
||||
}
|
||||
if stored[1].AccountID == nil || *stored[1].AccountID != second.ID || stored[1].TransportError != "upstream_stream_interrupted" {
|
||||
t.Fatalf("retry stream attempt = %#v", stored[1])
|
||||
}
|
||||
recorder.ensureStreamFailureAttempt(second, time.Now(), stream, "upstream_stream_interrupted")
|
||||
if got := recorder.snapshot(); len(got) != 2 {
|
||||
t.Fatalf("duplicate stream attempt = %#v", got)
|
||||
}
|
||||
inStream := newFailureAttemptRecorder(http.MethodPost, "/responses")
|
||||
inStream.captureStreamFailure(second, time.Now(), stream, StreamFailureDiagnostic{Body: []byte(`{"type":"response.failed"}`)})
|
||||
inStream.ensureStreamFailureAttempt(second, time.Now(), stream, "upstream_stream_error")
|
||||
if got := inStream.snapshot(); len(got) != 1 || got[0].Stage != "response_stream" {
|
||||
t.Fatalf("ensure after in-stream capture = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureStreamFailureAttemptSkipsNon2xx(t *testing.T) {
|
||||
recorder := newFailureAttemptRecorder(http.MethodPost, "/responses")
|
||||
credential := account.Credential{ID: 12, Name: "retry-b"}
|
||||
forbidden := &provider.Response{StatusCode: http.StatusForbidden, Status: "403 Forbidden"}
|
||||
recorder.ensureStreamFailureAttempt(credential, time.Now(), forbidden, "upstream_forbidden")
|
||||
if got := recorder.snapshot(); len(got) != 0 {
|
||||
t.Fatalf("non-2xx stream attempt = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailureAttemptRecorderClassifiesTransportErrorChain(t *testing.T) {
|
||||
dnsErr := &net.DNSError{Err: "no such host", Name: "api.example.test", IsNotFound: true}
|
||||
requestErr := &url.Error{Op: "Post", URL: "https://user:password@api.example.test/v1/responses?token=secret", Err: dnsErr}
|
||||
|
||||
@@ -243,6 +243,52 @@ func TestHTTPUpstreamFailureLeavesPaymentRecoveryKindToBilling(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryableResponseRotatesOnlyOnInternalBuildReasoningRecoveryFailure(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"}`)),
|
||||
ReasoningRecoveryFailed: true,
|
||||
}
|
||||
if !isRetryableResponse(failed, accountdomain.ProviderBuild) {
|
||||
t.Fatal("reasoning_recovery_failed 400 must rotate accounts")
|
||||
}
|
||||
if isRetryableResponse(failed, accountdomain.ProviderWeb) {
|
||||
t.Fatal("reasoning recovery failover must remain Build-specific")
|
||||
}
|
||||
|
||||
spoofed := &provider.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Header: failedHeader,
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":"unrelated bad request"}`)),
|
||||
}
|
||||
if isRetryableResponse(spoofed, accountdomain.ProviderBuild) {
|
||||
t.Fatal("an upstream-controlled compatibility warning must not trigger account rotation")
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -17,15 +18,20 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
ErrorQualityDegraded = "quality_degraded"
|
||||
qualityRetryFailOpen = "fail_open"
|
||||
qualityRetryFailClosed = "fail_closed"
|
||||
defaultQualityMaxAttempts = 6
|
||||
defaultQualityHoldTimeout = 30 * time.Second
|
||||
defaultQualityMinOutput = int64(8)
|
||||
defaultMissingThinkingCooldown = 12 * time.Hour
|
||||
lastErrorMissingThinking = accountdomain.LastErrorMissingThinking
|
||||
lastErrorMissingThinkingDisabled = accountdomain.LastErrorMissingThinkingDisabled
|
||||
ErrorQualityDegraded = "quality_degraded"
|
||||
qualityRetryFailOpen = "fail_open"
|
||||
qualityRetryFailClosed = "fail_closed"
|
||||
defaultQualityMaxAttempts = 6
|
||||
defaultQualityHoldTimeout = 30 * time.Second
|
||||
defaultQualityMinOutput = int64(8)
|
||||
defaultMinEncryptedBytes = 256
|
||||
defaultEncryptedBytesPerReasoningToken = 4
|
||||
defaultBurstFlushMS = int64(1000)
|
||||
defaultBurstMaxVisible = int64(32)
|
||||
defaultBurstMinReasoning = int64(80)
|
||||
defaultMissingThinkingCooldown = 12 * time.Hour
|
||||
lastErrorMissingThinking = accountdomain.LastErrorMissingThinking
|
||||
lastErrorMissingThinkingDisabled = accountdomain.LastErrorMissingThinkingDisabled
|
||||
// An empty stream that idles while held is treated as an account-quality
|
||||
// failure: the request can still rotate before any bytes reach the client.
|
||||
qualityIdleAccountCooldown = 15 * time.Minute
|
||||
@@ -47,13 +53,16 @@ type QualityRetryRuntime struct {
|
||||
AccountCooldown time.Duration
|
||||
// IdleAccountCooldown is applied to truly empty upstream streams
|
||||
// (idle timeout / empty peek). Missing-thinking still uses AccountCooldown.
|
||||
IdleAccountCooldown time.Duration
|
||||
IdleAccountCooldown time.Duration
|
||||
MinEncryptedBytes int
|
||||
EncryptedBytesPerReasoningToken int
|
||||
}
|
||||
|
||||
// QualityStreamSignals is the hold classifier input. Tests drive this
|
||||
// directly and via ObserveQualityChunk on SSE fixtures.
|
||||
type QualityStreamSignals struct {
|
||||
HasThinking bool
|
||||
HasThinking bool
|
||||
HasReasoningDelta bool
|
||||
// ReasoningStarted is an empty reasoning item or the Chat SSE stub
|
||||
// `: grok2api-reasoning-start`. That is not proof of thinking: 降智
|
||||
// still emits the stub, then dumps visible tokens with usage 0.
|
||||
@@ -61,6 +70,11 @@ type QualityStreamSignals struct {
|
||||
VisibleTokens int64
|
||||
ReasoningTokens int64
|
||||
OutputTokens int64
|
||||
EncryptedBytes int
|
||||
EncryptedFloor int64
|
||||
UsageReported bool
|
||||
FirstVisible bool
|
||||
VisibleFlushMS int64
|
||||
Terminal bool
|
||||
HoldExpired bool
|
||||
}
|
||||
@@ -100,6 +114,12 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime {
|
||||
if cfg.IdleAccountCooldown <= 0 {
|
||||
cfg.IdleAccountCooldown = qualityIdleAccountCooldown
|
||||
}
|
||||
if cfg.MinEncryptedBytes <= 0 {
|
||||
cfg.MinEncryptedBytes = defaultMinEncryptedBytes
|
||||
}
|
||||
if cfg.EncryptedBytesPerReasoningToken <= 0 {
|
||||
cfg.EncryptedBytesPerReasoningToken = defaultEncryptedBytesPerReasoningToken
|
||||
}
|
||||
cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted)
|
||||
return cfg
|
||||
}
|
||||
@@ -119,27 +139,100 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime {
|
||||
return normalizeQualityRetry(QualityRetryRuntime{})
|
||||
}
|
||||
|
||||
// encryptedThinkingFloor is max(minBytes, reasoningTokens*bytesPerToken).
|
||||
// A non-empty stub such as "gAAAA-cipher" is not thinking.
|
||||
func encryptedThinkingFloor(minBytes, bytesPerToken int, reasoningTokens int64) int64 {
|
||||
if minBytes <= 0 {
|
||||
minBytes = defaultMinEncryptedBytes
|
||||
}
|
||||
if bytesPerToken <= 0 {
|
||||
bytesPerToken = defaultEncryptedBytesPerReasoningToken
|
||||
}
|
||||
floor := int64(minBytes)
|
||||
if reasoningTokens > 0 {
|
||||
if reasoningTokens > math.MaxInt64/int64(bytesPerToken) {
|
||||
return math.MaxInt64
|
||||
}
|
||||
need := reasoningTokens * int64(bytesPerToken)
|
||||
if need > floor {
|
||||
floor = need
|
||||
}
|
||||
}
|
||||
return floor
|
||||
}
|
||||
|
||||
func qualityIsBurstDump(sig QualityStreamSignals, minOutput int64) bool {
|
||||
visible := sig.VisibleTokens
|
||||
floor := sig.EncryptedFloor
|
||||
if floor <= 0 {
|
||||
floor = encryptedThinkingFloor(0, 0, sig.ReasoningTokens)
|
||||
}
|
||||
barelyCeiling := int64(math.MaxInt64)
|
||||
if floor <= math.MaxInt64/2 {
|
||||
barelyCeiling = floor * 2
|
||||
}
|
||||
barelyCipher := sig.EncryptedBytes > 0 && int64(sig.EncryptedBytes) < barelyCeiling
|
||||
flushed := sig.FirstVisible && sig.VisibleFlushMS >= 0 && sig.VisibleFlushMS < defaultBurstFlushMS
|
||||
heavyReasoning := sig.ReasoningTokens >= defaultBurstMinReasoning
|
||||
shortVisible := visible > 0 && visible < defaultBurstMaxVisible
|
||||
// Hold timed out, then a short greeting dumped with a large reasoning bill
|
||||
// (TUI "你好" after 30s / 954 thinking tokens).
|
||||
if sig.HoldExpired && shortVisible && heavyReasoning {
|
||||
return true
|
||||
}
|
||||
// Cipher met the floor so HasThinking is true, but visible tokens then
|
||||
// dump in <1s with almost no answer (148 out / 140 reasoning in 0.7s).
|
||||
if flushed && shortVisible && heavyReasoning {
|
||||
return true
|
||||
}
|
||||
if barelyCipher && flushed && (visible >= minOutput || heavyReasoning) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ClassifyQualityHold decides whether a held stream may be forwarded.
|
||||
// Streamed thinking always delivers: reasoning/summary deltas, or a
|
||||
// reasoning item with encrypted_content. Usage.reasoning_tokens alone
|
||||
// does not — degraded upstreams fill that field without ciphertext or
|
||||
// deltas. A finished sample with enough visible output and no streamed
|
||||
// thinking is withheld.
|
||||
// Streamed thinking delivers: reasoning/summary deltas, or a reasoning item
|
||||
// whose encrypted_content meets the ciphertext floor. A non-empty stub such
|
||||
// as "gAAAA-cipher" is not thinking. Usage.reasoning_tokens alone does not —
|
||||
// degraded upstreams fill that field without ciphertext or deltas. A finished
|
||||
// sample with enough visible output and no streamed thinking is withheld.
|
||||
// Short replies below minOutput are delivered so "ok"/"yes" is not retried.
|
||||
// A hold timeout with no visible output is not fail-open: keep waiting for
|
||||
// more bytes or a stream abort so an empty hang is not flushed as HTTP 200.
|
||||
//
|
||||
// An empty reasoning stub is not thinking. Before the hold deadline, wait for
|
||||
// real evidence or a terminal event. If the deadline expires while the stream
|
||||
// is still open and already has visible output, the result is inconclusive:
|
||||
// release it without penalizing the account. A stub-only empty stream keeps
|
||||
// waiting for idle/terminal handling. This keeps HoldTimeout a real latency
|
||||
// bound without reopening the empty-stream 200 response path.
|
||||
// real evidence or a terminal event. A stub plus enough visible output at the
|
||||
// deadline is withheld — that is the TUI dump after 30s, not late ciphertext.
|
||||
// Stub-only empty streams keep waiting for idle/terminal handling.
|
||||
// HasThinking that is only a thin ciphertext dump after the hold (or a
|
||||
// barely-over-floor flush in <1s) is still withheld.
|
||||
func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict {
|
||||
if minOutput <= 0 {
|
||||
minOutput = defaultQualityMinOutput
|
||||
}
|
||||
// Readable reasoning deltas are direct proof and can preserve the original
|
||||
// low-latency release path. Ciphertext-only evidence remains provisional so
|
||||
// the classifier can observe visible output and terminal usage regardless of
|
||||
// how the SSE events were split across transport reads.
|
||||
if sig.HasReasoningDelta {
|
||||
return QualityDeliver
|
||||
}
|
||||
if sig.HasThinking {
|
||||
if !sig.FirstVisible && !sig.Terminal {
|
||||
return QualityWait
|
||||
}
|
||||
if qualityIsBurstDump(sig, minOutput) {
|
||||
if sig.Terminal {
|
||||
return QualityWithhold
|
||||
}
|
||||
return QualityWait
|
||||
}
|
||||
// The token-relative floor cannot be final until usage arrives. Preserve
|
||||
// HoldTimeout as the fail-open latency bound for still-open streams.
|
||||
if !sig.Terminal && !sig.HoldExpired && !sig.UsageReported {
|
||||
return QualityWait
|
||||
}
|
||||
return QualityDeliver
|
||||
}
|
||||
// Prefer observed/derived visible output. Total output includes reasoning
|
||||
@@ -151,10 +244,7 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
|
||||
output = sig.OutputTokens
|
||||
}
|
||||
enough := output >= minOutput
|
||||
if sig.ReasoningStarted && !sig.Terminal {
|
||||
if sig.HoldExpired && output > 0 {
|
||||
return QualityDeliver
|
||||
}
|
||||
if sig.ReasoningStarted && !sig.Terminal && !sig.HoldExpired {
|
||||
return QualityWait
|
||||
}
|
||||
if sig.Terminal {
|
||||
@@ -286,7 +376,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 || input.skipQualityHold {
|
||||
if !cfg.Enabled || !input.Streaming || input.ForcedEgressNodeID != 0 || input.skipQualityHold {
|
||||
return false
|
||||
}
|
||||
switch operation {
|
||||
@@ -294,26 +384,20 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
|
||||
default:
|
||||
return false
|
||||
}
|
||||
// TUI compaction is a normal /v1/responses body (no compaction_trigger).
|
||||
// Keep this defensive body check in addition to skipQualityHold so a caller
|
||||
// that bypasses CreateResponse cannot withhold a 100s+ summary as missing-thinking.
|
||||
// Context compaction is a system summary operation, not a normal reasoning
|
||||
// turn. Holding it can quarantine a healthy account for producing the
|
||||
// expected summary without streamed reasoning. Keep both compaction forms
|
||||
// excluded even if a caller reaches this gate without skipQualityHold.
|
||||
if isResponsesCompactionRequest(input.Body) {
|
||||
return false
|
||||
}
|
||||
if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole {
|
||||
return false
|
||||
}
|
||||
// Client-executed tools are safe to hold: their calls have not reached the
|
||||
// client yet, and completed results in the next request are immutable input.
|
||||
// Hosted tools are different. Retrying them can repeat an upstream search,
|
||||
// sandbox run, image job, or remote MCP call, so retain the old no-replay
|
||||
// safety boundary for any request that declares one.
|
||||
if qualityRequestHasReplayUnsafeHostedTools(input.Body) {
|
||||
return false
|
||||
}
|
||||
// Aliases are rewritten before this gate, so inspect the effective request
|
||||
// body instead of only the reasoning-capable base model. In particular,
|
||||
// grok-4.3-none becomes grok-4.3 plus an explicit disabled setting.
|
||||
// TUI commonly declares tools and follow-ups carry previous_response_id.
|
||||
// They still need quality classification, but replay safety is decided
|
||||
// separately: detecting a degraded response must not imply that an
|
||||
// account-bound or side-effecting request can run on another account.
|
||||
if qualityRequestDisablesReasoning(input.Body) {
|
||||
return false
|
||||
}
|
||||
@@ -323,6 +407,15 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
|
||||
return modeldomain.SupportsReasoningForProvider(route.Provider, route.UpstreamModel)
|
||||
}
|
||||
|
||||
// canReplayQualityHoldAcrossAccounts separates response classification from
|
||||
// retry authority. Stored Responses are account-bound, while hosted tools may
|
||||
// already have produced an external side effect before their held response is
|
||||
// rejected. Both may be held, audited, and penalized, but neither is replayed
|
||||
// on another account.
|
||||
func canReplayQualityHoldAcrossAccounts(input Input, ownership *inferencedomain.ResponseOwnership) bool {
|
||||
return ownership == nil && !qualityRequestHasReplayUnsafeHostedTools(input.Body)
|
||||
}
|
||||
|
||||
func qualityRequestHasReplayUnsafeHostedTools(body []byte) bool {
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) != nil || payload == nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -23,18 +24,23 @@ const (
|
||||
)
|
||||
|
||||
type qualityScanState struct {
|
||||
protocol string
|
||||
pending []byte
|
||||
hasThinking bool
|
||||
reasoningStarted bool
|
||||
visibleRunes int
|
||||
aggregateRunes int
|
||||
semanticOutput bool
|
||||
reasoningTokens int64
|
||||
outputTokens int64
|
||||
usage Usage
|
||||
responseID string
|
||||
terminal bool
|
||||
protocol string
|
||||
pending []byte
|
||||
hasThinking bool
|
||||
reasoningStarted bool
|
||||
visibleRunes int
|
||||
aggregateRunes int
|
||||
semanticOutput bool
|
||||
reasoningTokens int64
|
||||
outputTokens int64
|
||||
encryptedBytes int
|
||||
minEncryptedBytes int
|
||||
encryptedBytesPerReasoningToken int
|
||||
usage Usage
|
||||
responseID string
|
||||
terminal bool
|
||||
holdExpired bool
|
||||
firstVisibleAt time.Time
|
||||
}
|
||||
|
||||
type qualityReadResult struct {
|
||||
@@ -144,13 +150,30 @@ func (s *qualityScanState) signals() QualityStreamSignals {
|
||||
// Usage.reasoning_tokens is not proof of thinking. 降智 accounts report
|
||||
// hundreds of reasoning tokens on completed while the stream never sent
|
||||
// reasoning_text / reasoning_summary deltas (TUI shows no thoughts).
|
||||
// A non-empty encrypted_content stub is also not thinking until it meets
|
||||
// the ciphertext floor (default 256 bytes, or 4 bytes per reasoning token).
|
||||
reasoningTokens := max(s.reasoningTokens, s.usage.ReasoningTokens)
|
||||
floor := encryptedThinkingFloor(s.minEncryptedBytes, s.encryptedBytesPerReasoningToken, reasoningTokens)
|
||||
hasThinking := s.hasThinking || int64(s.encryptedBytes) >= floor
|
||||
firstVisible := !s.firstVisibleAt.IsZero()
|
||||
var flushMS int64
|
||||
if firstVisible {
|
||||
flushMS = time.Since(s.firstVisibleAt).Milliseconds()
|
||||
}
|
||||
return QualityStreamSignals{
|
||||
HasThinking: s.hasThinking,
|
||||
ReasoningStarted: s.reasoningStarted || s.hasThinking,
|
||||
VisibleTokens: visible,
|
||||
ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens),
|
||||
OutputTokens: output,
|
||||
Terminal: s.terminal,
|
||||
HasThinking: hasThinking,
|
||||
HasReasoningDelta: s.hasThinking,
|
||||
ReasoningStarted: s.reasoningStarted || hasThinking,
|
||||
VisibleTokens: visible,
|
||||
ReasoningTokens: reasoningTokens,
|
||||
OutputTokens: output,
|
||||
EncryptedBytes: s.encryptedBytes,
|
||||
EncryptedFloor: floor,
|
||||
UsageReported: s.usage.Reported,
|
||||
FirstVisible: firstVisible,
|
||||
VisibleFlushMS: flushMS,
|
||||
Terminal: s.terminal,
|
||||
HoldExpired: s.holdExpired,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,11 +202,15 @@ func ObserveQualityChunk(state *qualityScanState, chunk []byte) {
|
||||
state.reasoningStarted = true
|
||||
continue
|
||||
}
|
||||
if bytes.Equal(line, []byte(qualityReasoningEvidenceSSEComment)) {
|
||||
if bytes.HasPrefix(line, []byte(qualityReasoningEvidenceSSEComment)) {
|
||||
// Protocol converters cannot expose encrypted_content in every public
|
||||
// JSON contract. This internal SSE comment preserves that evidence.
|
||||
// JSON contract. This internal SSE comment preserves its byte length so
|
||||
// short stubs cannot bypass the ciphertext floor.
|
||||
state.reasoningStarted = true
|
||||
state.hasThinking = true
|
||||
value := strings.TrimSpace(strings.TrimPrefix(string(line), qualityReasoningEvidenceSSEComment))
|
||||
if count, err := strconv.Atoi(value); err == nil && count > state.encryptedBytes {
|
||||
state.encryptedBytes = count
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !bytes.HasPrefix(line, []byte("data:")) {
|
||||
@@ -277,6 +304,12 @@ type qualityResponsesOutputItem struct {
|
||||
} `json:"content"`
|
||||
}
|
||||
|
||||
func noteEncryptedBytes(state *qualityScanState, blob string) {
|
||||
if n := len(strings.TrimSpace(blob)); n > state.encryptedBytes {
|
||||
state.encryptedBytes = n
|
||||
}
|
||||
}
|
||||
|
||||
func noteResponsesReasoningItem(state *qualityScanState, item qualityResponsesOutputItem) {
|
||||
if !strings.EqualFold(strings.TrimSpace(item.Type), "reasoning") {
|
||||
return
|
||||
@@ -284,9 +317,7 @@ func noteResponsesReasoningItem(state *qualityScanState, item qualityResponsesOu
|
||||
if strings.TrimSpace(item.ID) != "" {
|
||||
state.reasoningStarted = true
|
||||
}
|
||||
if strings.TrimSpace(item.EncryptedContent) != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
noteEncryptedBytes(state, item.EncryptedContent)
|
||||
}
|
||||
|
||||
func observeQualityResponses(state *qualityScanState, payload []byte) {
|
||||
@@ -420,9 +451,7 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
|
||||
state.reasoningStarted = true
|
||||
case "redacted_thinking":
|
||||
state.reasoningStarted = true
|
||||
if strings.TrimSpace(event.ContentBlock.Data) != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
noteEncryptedBytes(state, event.ContentBlock.Data)
|
||||
case "text":
|
||||
if event.ContentBlock.Text != "" {
|
||||
noteVisibleContent(state, event.ContentBlock.Text)
|
||||
@@ -438,9 +467,9 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
|
||||
}
|
||||
if event.Delta.Type == "signature_delta" && strings.TrimSpace(event.Delta.Signature) != "" {
|
||||
// Anthropic Messages represents Responses encrypted_content as a
|
||||
// signature delta. A non-empty signature is encrypted thinking proof.
|
||||
// signature delta. Length is judged against the ciphertext floor.
|
||||
state.reasoningStarted = true
|
||||
state.hasThinking = true
|
||||
noteEncryptedBytes(state, event.Delta.Signature)
|
||||
}
|
||||
if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
|
||||
noteVisibleContent(state, event.Delta.Text)
|
||||
@@ -462,6 +491,9 @@ func noteVisibleContent(state *qualityScanState, text string) {
|
||||
if text == "" {
|
||||
return
|
||||
}
|
||||
if state.firstVisibleAt.IsZero() {
|
||||
state.firstVisibleAt = time.Now()
|
||||
}
|
||||
state.visibleRunes += utf8.RuneCountInString(text)
|
||||
}
|
||||
|
||||
@@ -471,7 +503,11 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string,
|
||||
return io.NopCloser(bytes.NewReader(nil)), QualityWait, Usage{}, "", errQualityEmptyStream
|
||||
}
|
||||
pump := newQualityReadPump(body)
|
||||
state := qualityScanState{protocol: protocol}
|
||||
state := qualityScanState{
|
||||
protocol: protocol,
|
||||
minEncryptedBytes: cfg.MinEncryptedBytes,
|
||||
encryptedBytesPerReasoningToken: cfg.EncryptedBytesPerReasoningToken,
|
||||
}
|
||||
var held bytes.Buffer
|
||||
holdTimer := time.NewTimer(cfg.HoldTimeout)
|
||||
defer holdTimer.Stop()
|
||||
@@ -492,6 +528,7 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string,
|
||||
_ = pump.Close()
|
||||
return io.NopCloser(bytes.NewReader(held.Bytes())), QualityWait, state.usage, state.responseID, qualityPeekAbortError(ctx, ctx.Err())
|
||||
case <-holdTimer.C:
|
||||
state.holdExpired = true
|
||||
sig.HoldExpired = true
|
||||
if verdict := ClassifyQualityHold(sig, cfg.MinOutputTokens); verdict != QualityWait {
|
||||
return newPrefixReplay(&held, pump), verdict, state.usage, state.responseID, nil
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -32,7 +33,7 @@ func TestClassifyQualityHold(t *testing.T) {
|
||||
sig QualityStreamSignals
|
||||
want QualityVerdict
|
||||
}{
|
||||
{name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 10}, want: QualityDeliver},
|
||||
{name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, HasReasoningDelta: true, VisibleTokens: 10}, want: QualityDeliver},
|
||||
{name: "usage reasoning tokens alone withhold", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, want: QualityWithhold},
|
||||
{name: "visible 32 no think withhold", sig: QualityStreamSignals{VisibleTokens: 32, Terminal: true}, want: QualityWithhold},
|
||||
{name: "output 40 no think withhold", sig: QualityStreamSignals{OutputTokens: 40, Terminal: true}, want: QualityWithhold},
|
||||
@@ -41,7 +42,7 @@ func TestClassifyQualityHold(t *testing.T) {
|
||||
{name: "empty terminal waits for transport handling", sig: QualityStreamSignals{Terminal: true}, want: QualityWait},
|
||||
{name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold},
|
||||
{name: "stub midstream waits even with enough visible", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64}, want: QualityWait},
|
||||
{name: "stub hold expiry is inconclusive and delivers", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, HoldExpired: true}, want: QualityDeliver},
|
||||
{name: "stub hold expiry with enough visible withholds", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, HoldExpired: true}, want: QualityWithhold},
|
||||
{name: "stub-only hold expiry keeps waiting", sig: QualityStreamSignals{ReasoningStarted: true, HoldExpired: true}, want: QualityWait},
|
||||
{name: "stub terminal enough withhold", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, Terminal: true}, want: QualityWithhold},
|
||||
{name: "wait for more", sig: QualityStreamSignals{VisibleTokens: 8}, want: QualityWait},
|
||||
@@ -59,6 +60,96 @@ func TestClassifyQualityHold(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyQualityHoldBurst(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
name string
|
||||
sig QualityStreamSignals
|
||||
want QualityVerdict
|
||||
}{
|
||||
{
|
||||
name: "terminal hold-expired hello dump withholds",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 2, ReasoningTokens: 954, EncryptedBytes: 4000, EncryptedFloor: 3816, UsageReported: true, FirstVisible: true, HoldExpired: true, Terminal: true},
|
||||
want: QualityWithhold,
|
||||
},
|
||||
{
|
||||
name: "hold-expired long answer delivers",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 200, ReasoningTokens: 954, EncryptedBytes: 8000, EncryptedFloor: 3816, UsageReported: true, FirstVisible: true, HoldExpired: true},
|
||||
want: QualityDeliver,
|
||||
},
|
||||
{
|
||||
name: "non-terminal barely-over-floor flush keeps observing",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 300, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100},
|
||||
want: QualityWait,
|
||||
},
|
||||
{
|
||||
name: "terminal barely-over-floor flush withholds",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 300, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100, Terminal: true},
|
||||
want: QualityWithhold,
|
||||
},
|
||||
{
|
||||
name: "large cipher flush delivers",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 2000, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100},
|
||||
want: QualityDeliver,
|
||||
},
|
||||
{
|
||||
name: "non-terminal floor-met short burst keeps observing",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 3, ReasoningTokens: 1371, EncryptedBytes: 8000, EncryptedFloor: 5484, UsageReported: true, FirstVisible: true, VisibleFlushMS: 200},
|
||||
want: QualityWait,
|
||||
},
|
||||
{
|
||||
name: "floor-met short visible fast dump withholds",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 3, ReasoningTokens: 1371, EncryptedBytes: 8000, EncryptedFloor: 5484, UsageReported: true, FirstVisible: true, VisibleFlushMS: 200, Terminal: true},
|
||||
want: QualityWithhold,
|
||||
},
|
||||
{
|
||||
name: "floor-met 8 visible 140 reasoning in under 1s withholds",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 8, ReasoningTokens: 140, EncryptedBytes: 2000, EncryptedFloor: 560, UsageReported: true, FirstVisible: true, VisibleFlushMS: 660, Terminal: true},
|
||||
want: QualityWithhold,
|
||||
},
|
||||
{
|
||||
name: "floor-met long visible fast flush delivers",
|
||||
sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 80, ReasoningTokens: 140, EncryptedBytes: 2000, EncryptedFloor: 560, UsageReported: true, FirstVisible: true, VisibleFlushMS: 200, Terminal: true},
|
||||
want: QualityDeliver,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := ClassifyQualityHold(test.sig, 8); got != test.want {
|
||||
t.Fatalf("ClassifyQualityHold() = %s, want %s (%#v)", got, test.want, test.sig)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyQualityHoldBurstUsesConfiguredFloor(t *testing.T) {
|
||||
t.Parallel()
|
||||
configuredHigh := QualityStreamSignals{
|
||||
HasThinking: true, VisibleTokens: 40, ReasoningTokens: 100,
|
||||
EncryptedBytes: 1100, EncryptedFloor: 1024, UsageReported: true,
|
||||
FirstVisible: true, VisibleFlushMS: 100, Terminal: true,
|
||||
}
|
||||
if got := ClassifyQualityHold(configuredHigh, 8); got != QualityWithhold {
|
||||
t.Fatalf("configured high floor verdict = %s, want withhold", got)
|
||||
}
|
||||
configuredLow := QualityStreamSignals{
|
||||
HasThinking: true, VisibleTokens: 40, ReasoningTokens: 60,
|
||||
EncryptedBytes: 300, EncryptedFloor: 64, UsageReported: true,
|
||||
FirstVisible: true, VisibleFlushMS: 100, Terminal: true,
|
||||
}
|
||||
if got := ClassifyQualityHold(configuredLow, 8); got != QualityDeliver {
|
||||
t.Fatalf("configured low floor verdict = %s, want deliver", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptedThinkingFloorSaturates(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := encryptedThinkingFloor(256, 16, math.MaxInt64); got != math.MaxInt64 {
|
||||
t.Fatalf("overflowing floor = %d, want %d", got, int64(math.MaxInt64))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideQualityRetry(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := DecideQualityRetry(QualityDeliver, 0, 2, qualityRetryFailOpen); got != QualityActionDeliver {
|
||||
@@ -289,10 +380,11 @@ func TestObserveQualityChunkShortNoThinkIgnoresFakeReasoningUsage(t *testing.T)
|
||||
|
||||
func TestObserveQualityConvertedEncryptedThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
cipher := strings.Repeat("A", defaultMinEncryptedBytes*8)
|
||||
source := sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`,
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+cipher+`"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)
|
||||
@@ -326,6 +418,45 @@ func TestObserveQualityConvertedEncryptedThinking(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityConvertedShortEncryptedStubDoesNotBypassFloor(t *testing.T) {
|
||||
t.Parallel()
|
||||
const stub = "gAAAA-cipher"
|
||||
source := sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`,
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+stub+`"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
operation string
|
||||
protocol string
|
||||
options conversation.ResponseOptions
|
||||
}{
|
||||
{name: "chat", operation: conversation.OperationChat, protocol: qualityProtocolChat},
|
||||
{name: "messages", operation: conversation.OperationMessages, protocol: qualityProtocolAnthropic, options: conversation.ResponseOptions{AnthropicThinking: true}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
converted, err := io.ReadAll(conversation.ConvertResponseStreamWithOptions(
|
||||
io.NopCloser(strings.NewReader(source)), test.operation, test.options,
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := qualityScanState{protocol: test.protocol}
|
||||
ObserveQualityChunk(&state, converted)
|
||||
sig := state.signals()
|
||||
if sig.HasThinking || sig.EncryptedBytes != len(stub) || !sig.ReasoningStarted {
|
||||
t.Fatalf("converted short stub signals = %#v\n%s", sig, converted)
|
||||
}
|
||||
if got := ClassifyQualityHold(sig, 32); got != QualityWithhold {
|
||||
t.Fatalf("converted short stub verdict = %s, want withhold", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
@@ -350,12 +481,21 @@ func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) {
|
||||
|
||||
func TestObserveQualityChunkAnthropicSignatureIsThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
state := qualityScanState{protocol: qualityProtocolAnthropic}
|
||||
ObserveQualityChunk(&state, []byte(sse(
|
||||
short := qualityScanState{protocol: qualityProtocolAnthropic}
|
||||
ObserveQualityChunk(&short, []byte(sse(
|
||||
`data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"gAAAA-cipher"}}`,
|
||||
)))
|
||||
if sig := short.signals(); sig.HasThinking || !sig.ReasoningStarted || sig.EncryptedBytes == 0 {
|
||||
t.Fatalf("short Anthropic signature stub must not count as thinking: %#v", sig)
|
||||
}
|
||||
|
||||
cipher := strings.Repeat("A", defaultMinEncryptedBytes)
|
||||
state := qualityScanState{protocol: qualityProtocolAnthropic}
|
||||
ObserveQualityChunk(&state, []byte(sse(
|
||||
`data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"`+cipher+`"}}`,
|
||||
)))
|
||||
if sig := state.signals(); !sig.HasThinking || !sig.ReasoningStarted {
|
||||
t.Fatalf("non-empty Anthropic signature must count as encrypted thinking: %#v", sig)
|
||||
t.Fatalf("floor-sized Anthropic signature must count as encrypted thinking: %#v", sig)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,20 +532,54 @@ func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) {
|
||||
t.Fatalf("streamed reasoning summary should deliver: %#v", realSig)
|
||||
}
|
||||
|
||||
short := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&short, []byte(sse(
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)))
|
||||
shortSig := short.signals()
|
||||
if shortSig.HasThinking {
|
||||
t.Fatalf("short encrypted stub must not count as thinking: %#v", shortSig)
|
||||
}
|
||||
if shortSig.EncryptedBytes == 0 || !shortSig.ReasoningStarted || shortSig.ReasoningTokens != 60 {
|
||||
t.Fatalf("short encrypted stub signals = %#v", shortSig)
|
||||
}
|
||||
if ClassifyQualityHold(shortSig, 32) != QualityWithhold {
|
||||
t.Fatalf("short encrypted stub must withhold: %#v", shortSig)
|
||||
}
|
||||
|
||||
cipher := strings.Repeat("A", defaultMinEncryptedBytes*8)
|
||||
encrypted := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&encrypted, []byte(sse(
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"hello hello hello hello hello hello hello hello"}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+cipher+`"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)))
|
||||
encSig := encrypted.signals()
|
||||
if !encSig.HasThinking || encSig.ReasoningTokens != 60 {
|
||||
if !encSig.HasThinking || encSig.ReasoningTokens != 60 || encSig.EncryptedBytes < defaultMinEncryptedBytes {
|
||||
t.Fatalf("encrypted reasoning item must count as thinking: %#v", encSig)
|
||||
}
|
||||
if ClassifyQualityHold(encSig, 32) != QualityDeliver {
|
||||
t.Fatalf("encrypted thinking should deliver: %#v", encSig)
|
||||
}
|
||||
|
||||
floorCipher := strings.Repeat("A", defaultMinEncryptedBytes)
|
||||
undersized := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&undersized, []byte(sse(
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+floorCipher+`"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":1200,"output_tokens_details":{"reasoning_tokens":1000}}}}`,
|
||||
)))
|
||||
underSig := undersized.signals()
|
||||
if underSig.HasThinking {
|
||||
t.Fatalf("256B cipher must not satisfy 1000 reasoning tokens: %#v", underSig)
|
||||
}
|
||||
if ClassifyQualityHold(underSig, 32) != QualityWithhold {
|
||||
t.Fatalf("undersized cipher vs usage must withhold: %#v", underSig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkEmptyReasoningStubIsNotThinking(t *testing.T) {
|
||||
@@ -478,6 +652,80 @@ func TestPeekQualityStreamThinkingDeliversRemainder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeekQualityStreamCipherBurstWaitsAcrossEventSplits(t *testing.T) {
|
||||
t.Parallel()
|
||||
cipher := strings.Repeat("A", 400)
|
||||
createdAndCipher := sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":80,"output_tokens_details":{"reasoning_tokens":80}}}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+cipher+`"}}`,
|
||||
)
|
||||
visible := sse(`data: {"type":"response.output_text.delta","delta":"你好"}`)
|
||||
completed := sse(`data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":82,"output_tokens_details":{"reasoning_tokens":80}}}}`)
|
||||
cfg := QualityRetryRuntime{MinOutputTokens: 8, HoldTimeout: 2 * time.Second}
|
||||
|
||||
coalesced, coalescedVerdict, _, _, err := peekQualityStream(
|
||||
context.Background(), io.NopCloser(strings.NewReader(createdAndCipher+visible+completed)), qualityProtocolResponses, cfg,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = coalesced.Close()
|
||||
if coalescedVerdict != QualityWithhold {
|
||||
t.Fatalf("coalesced verdict = %s, want withhold", coalescedVerdict)
|
||||
}
|
||||
|
||||
reader, writer := io.Pipe()
|
||||
type peekResult struct {
|
||||
replay io.ReadCloser
|
||||
verdict QualityVerdict
|
||||
err error
|
||||
}
|
||||
done := make(chan peekResult, 1)
|
||||
go func() {
|
||||
replay, verdict, _, _, peekErr := peekQualityStream(context.Background(), reader, qualityProtocolResponses, cfg)
|
||||
done <- peekResult{replay: replay, verdict: verdict, err: peekErr}
|
||||
}()
|
||||
if _, err := io.WriteString(writer, createdAndCipher); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case result := <-done:
|
||||
if result.replay != nil {
|
||||
_ = result.replay.Close()
|
||||
}
|
||||
t.Fatalf("ciphertext-only partial stream returned early: verdict=%s err=%v", result.verdict, result.err)
|
||||
case <-time.After(40 * time.Millisecond):
|
||||
}
|
||||
if _, err := io.WriteString(writer, visible); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case result := <-done:
|
||||
if result.replay != nil {
|
||||
_ = result.replay.Close()
|
||||
}
|
||||
t.Fatalf("non-terminal burst was finalized early: verdict=%s err=%v", result.verdict, result.err)
|
||||
case <-time.After(40 * time.Millisecond):
|
||||
}
|
||||
if _, err := io.WriteString(writer, completed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case result := <-done:
|
||||
if result.replay != nil {
|
||||
_ = result.replay.Close()
|
||||
}
|
||||
if result.err != nil || result.verdict != QualityWithhold {
|
||||
t.Fatalf("split verdict=%s err=%v, want withhold", result.verdict, result.err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("split terminal stream did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeekQualityStreamWithholdsNoThinkEnough(t *testing.T) {
|
||||
t.Parallel()
|
||||
content := strings.Repeat("abcd", 16) // 64 runes → 16 tokens... need 32 tokens = 128 runes
|
||||
@@ -650,8 +898,8 @@ func TestPeekQualityStreamHoldTimeoutDeliversStartedReasoningAndPreservesLateEvi
|
||||
if elapsed := time.Since(started); elapsed < 20*time.Millisecond || elapsed > 200*time.Millisecond {
|
||||
t.Fatalf("peek returned after %s, want the 30ms hold timeout", elapsed)
|
||||
}
|
||||
if verdict != QualityDeliver {
|
||||
t.Fatalf("started reasoning at hold timeout verdict = %s, want deliver", verdict)
|
||||
if verdict != QualityWithhold {
|
||||
t.Fatalf("started reasoning stub at hold timeout verdict = %s, want withhold", verdict)
|
||||
}
|
||||
close(continueWrite)
|
||||
body, err := io.ReadAll(replay)
|
||||
@@ -971,24 +1219,24 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
|
||||
t.Fatal("forced egress must not hold")
|
||||
}
|
||||
owned := inferencedomain.ResponseOwnership{ResponseID: "r1", AccountID: 1}
|
||||
if shouldHoldQualityStream(input, &owned, route, audit.OperationChat, cfg) {
|
||||
t.Fatal("pinned response must not hold")
|
||||
if !shouldHoldQualityStream(input, &owned, route, audit.OperationChat, cfg) {
|
||||
t.Fatal("pinned previous_response_id must still hold on missing thinking")
|
||||
}
|
||||
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")
|
||||
t.Fatal("compaction must not enter missing-thinking hold")
|
||||
}
|
||||
classified := input
|
||||
classified.skipQualityHold = true
|
||||
if shouldHoldQualityStream(classified, nil, route, audit.OperationResponses, cfg) {
|
||||
t.Fatal("gateway-classified compaction must not hold")
|
||||
t.Fatal("explicit skipQualityHold 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")
|
||||
t.Fatal("tui compaction prompt must not enter missing-thinking hold")
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
@@ -1072,8 +1320,8 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
|
||||
if !qualityRequestHasReplayUnsafeHostedTools(request.Body) {
|
||||
t.Fatal("fixture must be classified as replay-unsafe hosted tooling")
|
||||
}
|
||||
if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
|
||||
t.Fatal("hosted tools must not be held because account retry can execute them again")
|
||||
if !shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
|
||||
t.Fatal("hosted tools must still hold; TUI always declares them")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1094,6 +1342,185 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanReplayQualityHoldAcrossAccounts(t *testing.T) {
|
||||
t.Parallel()
|
||||
plain := Input{Body: []byte(`{"input":"hello"}`)}
|
||||
if !canReplayQualityHoldAcrossAccounts(plain, nil) {
|
||||
t.Fatal("stateless text request should allow account retry")
|
||||
}
|
||||
owned := inferencedomain.ResponseOwnership{ResponseID: "resp_1", AccountID: 1}
|
||||
if canReplayQualityHoldAcrossAccounts(plain, &owned) {
|
||||
t.Fatal("stored response must remain pinned to its owner account")
|
||||
}
|
||||
hosted := Input{Body: []byte(`{"tools":[{"type":"web_search"}],"input":"hello"}`)}
|
||||
if canReplayQualityHoldAcrossAccounts(hosted, nil) {
|
||||
t.Fatal("hosted tool must not be replayed across accounts")
|
||||
}
|
||||
clientTool := Input{Body: []byte(`{"tools":[{"type":"function","name":"read_file"}],"input":"hello"}`)}
|
||||
if !canReplayQualityHoldAcrossAccounts(clientTool, nil) {
|
||||
t.Fatal("client-executed tool declaration is safe to retry before delivery")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptLoopQualityHoldPreservesReplaySafety(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
previous bool
|
||||
body string
|
||||
onExhausted string
|
||||
wantError bool
|
||||
empty bool
|
||||
wantMissing bool
|
||||
}{
|
||||
{
|
||||
name: "previous response remains account bound",
|
||||
previous: true,
|
||||
body: `{"model":"grok-4.6","previous_response_id":"resp-root","input":"continue","stream":true}`,
|
||||
onExhausted: qualityRetryFailClosed,
|
||||
wantError: true,
|
||||
wantMissing: true,
|
||||
},
|
||||
{
|
||||
name: "hosted tool fail closed executes once",
|
||||
body: `{"model":"grok-4.6","tools":[{"type":"web_search"}],"input":"search","stream":true}`,
|
||||
onExhausted: qualityRetryFailClosed,
|
||||
wantError: true,
|
||||
wantMissing: true,
|
||||
},
|
||||
{
|
||||
name: "hosted tool fail open delivers same attempt",
|
||||
body: `{"model":"grok-4.6","tools":[{"type":"web_search"}],"input":"search","stream":true}`,
|
||||
onExhausted: qualityRetryFailOpen,
|
||||
wantMissing: true,
|
||||
},
|
||||
{
|
||||
name: "hosted tool empty stream executes once",
|
||||
body: `{"model":"grok-4.6","tools":[{"type":"web_search"}],"input":"search","stream":true}`,
|
||||
onExhausted: qualityRetryFailClosed,
|
||||
wantError: true,
|
||||
empty: true,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-replay-safety.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
responseRepo := relational.NewResponseRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
|
||||
credentials := make([]accountdomain.Credential, 0, 2)
|
||||
for index, name := range []string{"quality-safe-a", "quality-safe-b"} {
|
||||
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, Name: name, SourceKey: name,
|
||||
EncryptedAccessToken: name, EncryptedRefreshToken: "refresh-" + name,
|
||||
ExpiresAt: time.Now().Add(time.Hour), Enabled: true,
|
||||
AuthStatus: accountdomain.AuthStatusActive, Priority: 200 - index, MaxConcurrent: 1,
|
||||
})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
credentials = append(credentials, credential)
|
||||
}
|
||||
if err := modelRepo.UpsertDiscovered(ctx, accountdomain.ProviderBuild, []string{"grok-4.6"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, credential := range credentials {
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-4.6"}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
key, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "quality-safe-key", Prefix: "qsafe", SecretHash: strings.Repeat("8", 64),
|
||||
EncryptedSecret: "encrypted", Enabled: true, RPMLimit: 120, MaxConcurrent: 8,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if test.previous {
|
||||
now := time.Now().UTC()
|
||||
if err := responseRepo.Save(ctx, inferencedomain.ResponseOwnership{
|
||||
ResponseID: "resp-root", AccountID: credentials[0].ID, ClientKeyID: key.ID,
|
||||
Provider: accountdomain.ProviderBuild, PromptCacheKey: "session-root",
|
||||
CreatedAt: now, UpdatedAt: now, ExpiresAt: now.Add(time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
noThinking := sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp-bad","model":"grok-4.6"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("bad ", 20)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp-bad","model":"grok-4.6","usage":{"output_tokens":40,"output_tokens_details":{"reasoning_tokens":0}}}}`,
|
||||
)
|
||||
thinking := sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp-good","model":"grok-4.6"}}`,
|
||||
`data: {"type":"response.reasoning_summary_text.delta","delta":"real reasoning"}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"good answer"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp-good","model":"grok-4.6","usage":{"output_tokens":40,"output_tokens_details":{"reasoning_tokens":20}}}}`,
|
||||
)
|
||||
firstBody := noThinking
|
||||
if test.empty {
|
||||
firstBody = ""
|
||||
}
|
||||
adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{
|
||||
credentials[0].ID: {{status: http.StatusOK, body: firstBody}},
|
||||
credentials[1].ID: {{status: http.StatusOK, body: thinking}},
|
||||
}}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3)
|
||||
service.UpdateQualityRetry(QualityRetryRuntime{
|
||||
Enabled: true, MaxAttempts: 2, MinOutputTokens: 8,
|
||||
OnExhausted: test.onExhausted, HoldTimeout: time.Second,
|
||||
})
|
||||
|
||||
input := Input{
|
||||
RequestID: "req-quality-safe", ClientKey: key, PublicModel: "grok-4.6",
|
||||
Streaming: true, Body: []byte(test.body),
|
||||
}
|
||||
if test.previous {
|
||||
input.PreviousResponseID = "resp-root"
|
||||
}
|
||||
result, requestErr := service.CreateResponse(ctx, input)
|
||||
var responseBody []byte
|
||||
if result != nil {
|
||||
responseBody, _ = io.ReadAll(result.Body)
|
||||
result.Finalize(Usage{}, "", "")
|
||||
_ = result.Body.Close()
|
||||
}
|
||||
if (requestErr != nil) != test.wantError {
|
||||
t.Fatalf("request error = %v, wantError=%t", requestErr, test.wantError)
|
||||
}
|
||||
if !test.wantError && !strings.Contains(string(responseBody), "bad ") {
|
||||
t.Fatalf("fail-open did not deliver the held first attempt: %s", responseBody)
|
||||
}
|
||||
attempts := adapter.Attempts()
|
||||
if len(attempts) != 1 || attempts[0] != credentials[0].ID {
|
||||
t.Fatalf("request crossed its replay-safety boundary, attempts=%v", attempts)
|
||||
}
|
||||
cooled, err := accountRepo.Get(ctx, credentials[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cooled.CooldownUntil == nil || (test.wantMissing && cooled.LastError != lastErrorMissingThinking) {
|
||||
t.Fatalf("degraded account was not penalized: %#v", cooled)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptLoopQualityHold(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-hold-loop.db"))
|
||||
@@ -1409,7 +1836,7 @@ func TestAttemptLoopQualityFailOpenFallbackAndTotalAttemptCap(t *testing.T) {
|
||||
func TestNormalizeQualityRetryDefaults(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := normalizeQualityRetry(QualityRetryRuntime{Enabled: true})
|
||||
if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 8 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 30*time.Second || got.AccountCooldown != 12*time.Hour || got.IdleAccountCooldown != 15*time.Minute {
|
||||
if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 8 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 30*time.Second || got.AccountCooldown != 12*time.Hour || got.IdleAccountCooldown != 15*time.Minute || got.MinEncryptedBytes != defaultMinEncryptedBytes || got.EncryptedBytesPerReasoningToken != defaultEncryptedBytesPerReasoningToken {
|
||||
t.Fatalf("defaults = %#v", got)
|
||||
}
|
||||
}
|
||||
@@ -1018,6 +1018,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
|
||||
// A lease recovery probe stays on exactly one account and one rendered proxy
|
||||
// identity. Retrying the same pinned account would provide neither failover
|
||||
// nor new evidence and can multiply a slow/failing probe.
|
||||
holdCfg := s.qualityRetryConfig()
|
||||
qualityHoldEnabled := shouldHoldQualityStream(input, ownership, route, operation, holdCfg)
|
||||
qualityCrossAccountReplay := canReplayQualityHoldAcrossAccounts(input, ownership)
|
||||
attemptPolicy := newRequestRoutingAttemptPolicy(int(s.maxAttempts.Load()), ownership != nil || input.ForcedAccountID != 0)
|
||||
idempotencyID, _ := security.NewOpaqueToken(18)
|
||||
pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel)
|
||||
@@ -1032,8 +1035,6 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
|
||||
excluded := make(map[uint64]bool)
|
||||
failureFingerprints := make(map[string]int)
|
||||
authRecoveryAttempted := make(map[uint64]bool)
|
||||
holdCfg := s.qualityRetryConfig()
|
||||
qualityHoldEnabled := shouldHoldQualityStream(input, ownership, route, operation, holdCfg)
|
||||
// Count accounts that actually reached the upstream. Credential-only skips
|
||||
// do not consume the quality retry budget; refreshes stay on the same account.
|
||||
qualityAccountAttempts := 0
|
||||
@@ -1118,26 +1119,10 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
|
||||
}
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.ErrorCode = errorCode
|
||||
attempts := failureAttempts.snapshot()
|
||||
if !successful && len(attempts) == 0 {
|
||||
statusCode := response.StatusCode
|
||||
failureAttempts.append(audit.Attempt{
|
||||
Source: audit.AttemptSourceUpstreamHTTP,
|
||||
Stage: "response_stream",
|
||||
AccountID: auditAccountID(credential.ID),
|
||||
AccountName: credential.Name,
|
||||
Method: http.MethodPost,
|
||||
RequestPath: sanitizeRequestPath(path),
|
||||
UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL),
|
||||
StartedAt: upstreamStartedAt.UTC(),
|
||||
DurationMS: time.Since(upstreamStartedAt).Milliseconds(),
|
||||
UpstreamStatusCode: &statusCode,
|
||||
UpstreamStatus: response.Status,
|
||||
ResponseHeaders: sanitizeDiagnosticHeaders(response.Header),
|
||||
TransportError: errorCode,
|
||||
})
|
||||
attempts = failureAttempts.snapshot()
|
||||
if !successful && response.StatusCode >= http.StatusOK && response.StatusCode < http.StatusMultipleChoices {
|
||||
failureAttempts.ensureStreamFailureAttempt(credential, upstreamStartedAt, response, errorCode)
|
||||
}
|
||||
attempts := failureAttempts.snapshot()
|
||||
if !successful || len(attempts) > 0 {
|
||||
record.Attempts = attempts
|
||||
}
|
||||
@@ -1611,14 +1596,16 @@ attemptLoop:
|
||||
}
|
||||
writeCancel()
|
||||
}
|
||||
if shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) {
|
||||
if !qualityCrossAccountReplay || shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
response.Body = replay
|
||||
hasNextAccount := attemptPolicy.hasNext(attempt) && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted)
|
||||
hasNextAccount = hasNextAccount && qualityAccountAttempts < holdCfg.MaxAttempts
|
||||
hasNextAccount := qualityCrossAccountReplay && attemptPolicy.hasNext(attempt) && qualityAccountAttempts < holdCfg.MaxAttempts
|
||||
if hasNextAccount {
|
||||
hasNextAccount = selection != nil && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted)
|
||||
}
|
||||
commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted)
|
||||
if verdict == QualityWithhold {
|
||||
s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown)
|
||||
@@ -2092,8 +2079,18 @@ func isRetryable(status int) bool {
|
||||
return status == 402 || status == 403 || status == 429 || status >= 500
|
||||
}
|
||||
|
||||
func isReasoningRecoveryFailedResponse(response *provider.Response, upstreamProvider accountdomain.Provider) bool {
|
||||
return upstreamProvider == accountdomain.ProviderBuild && response != nil && response.ReasoningRecoveryFailed
|
||||
}
|
||||
|
||||
func isRetryableResponse(response *provider.Response, upstreamProvider accountdomain.Provider) bool {
|
||||
if response == nil || !isRetryable(response.StatusCode) {
|
||||
if response == nil {
|
||||
return false
|
||||
}
|
||||
if response.StatusCode == http.StatusBadRequest && isReasoningRecoveryFailedResponse(response, upstreamProvider) {
|
||||
return true
|
||||
}
|
||||
if !isRetryable(response.StatusCode) {
|
||||
return false
|
||||
}
|
||||
// Account-scoped payment failures must always rotate accounts.
|
||||
|
||||
@@ -3064,6 +3064,17 @@ func TestGatewaySafetyRejectionDoesNotTouchAccountState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
logs, total, err := auditRepo.List(ctx, 0, 10)
|
||||
if err != nil || total != 1 || len(logs) != 1 {
|
||||
t.Fatalf("audit list = %#v, total=%d, err=%v", logs, total, err)
|
||||
}
|
||||
detail, err := auditRepo.Get(ctx, logs[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.AttemptCount != 1 || len(detail.Attempts) != 1 || detail.Attempts[0].Stage != "upstream_response" || detail.Attempts[0].UpstreamStatusCode == nil || *detail.Attempts[0].UpstreamStatusCode != http.StatusForbidden {
|
||||
t.Fatalf("terminal 403 attempts = %#v", detail.Attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayConsoleDPoPRequirementStopsAfterOneAccount(t *testing.T) {
|
||||
@@ -3492,6 +3503,96 @@ func TestGatewayGeneric429CoolsAccountAndRotates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayRetryStreamFailureRecordsPrior429AndRetryStream(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "retry-stream-failure.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
responseRepo := relational.NewResponseRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
|
||||
credentials := make([]account.Credential, 0, 2)
|
||||
for index, name := range []string{"retry-a", "retry-b"} {
|
||||
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: name, SourceKey: name, EncryptedAccessToken: name,
|
||||
ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: account.AuthStatusActive,
|
||||
Priority: 200 - index, MaxConcurrent: 1,
|
||||
})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
credentials = append(credentials, credential)
|
||||
}
|
||||
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-retry-stream"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, credential := range credentials {
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-retry-stream"}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
clientKey, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "retry-stream-key", Prefix: "retrystream", SecretHash: strings.Repeat("4", 64), EncryptedSecret: "encrypted",
|
||||
Enabled: true, RPMLimit: 120, MaxConcurrent: 8,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exhausted := `{"code":"subscription:free-usage-exhausted","error":"You've used all the included free usage for model grok-4.6 for now. Usage resets over a rolling 24-hour window — tokens (actual/limit): 558975/500000."}`
|
||||
adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{
|
||||
credentials[0].ID: {{status: http.StatusTooManyRequests, body: exhausted}},
|
||||
credentials[1].ID: {{status: http.StatusOK, header: http.Header{"Content-Type": {"text/event-stream"}}, body: "data: {\"type\":\"response.created\"}\n\n"}},
|
||||
}}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3)
|
||||
|
||||
result, err := service.CreateResponse(ctx, Input{
|
||||
RequestID: "req-retry-stream", ClientKey: clientKey, PublicModel: "grok-retry-stream",
|
||||
Body: []byte(`{"model":"grok-retry-stream","input":"hello"}`), Streaming: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result.Finalize(Usage{}, "", "upstream_stream_interrupted")
|
||||
_ = result.Body.Close()
|
||||
if attempts := adapter.Attempts(); len(attempts) != 2 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID {
|
||||
t.Fatalf("429 must rotate before stream failure, attempts=%#v", attempts)
|
||||
}
|
||||
|
||||
logs, _, err := auditRepo.List(ctx, 0, 10)
|
||||
if err != nil || len(logs) == 0 {
|
||||
t.Fatalf("audits = %#v, err = %v", logs, err)
|
||||
}
|
||||
detail, err := auditRepo.Get(ctx, logs[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.ErrorCode != "upstream_stream_interrupted" || detail.AccountID == nil || *detail.AccountID != credentials[1].ID {
|
||||
t.Fatalf("audit = %#v", detail)
|
||||
}
|
||||
if detail.AttemptCount != 2 || len(detail.Attempts) != 2 {
|
||||
t.Fatalf("attempt count = %d stored = %d, attempts=%#v", detail.AttemptCount, len(detail.Attempts), detail.Attempts)
|
||||
}
|
||||
first, second := detail.Attempts[0], detail.Attempts[1]
|
||||
if first.Stage != "upstream_response" || first.UpstreamStatusCode == nil || *first.UpstreamStatusCode != http.StatusTooManyRequests || first.AccountID == nil || *first.AccountID != credentials[0].ID {
|
||||
t.Fatalf("first attempt = %#v", first)
|
||||
}
|
||||
if second.Stage != "response_stream" || second.UpstreamStatusCode == nil || *second.UpstreamStatusCode != http.StatusOK || second.AccountID == nil || *second.AccountID != credentials[1].ID || second.TransportError != "upstream_stream_interrupted" {
|
||||
t.Fatalf("retry stream attempt = %#v", second)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayNonAccount5xxSoftCoolsAndRotates(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "soft-5xx.db"))
|
||||
|
||||
@@ -297,7 +297,9 @@ type QualityGuardRequestRetryConfig struct {
|
||||
AccountCooldown Duration `yaml:"accountCooldown"`
|
||||
// IdleAccountCooldown cools an account after a truly empty upstream
|
||||
// stream. Independent of accountCooldown (missing-thinking). Zero uses 15m.
|
||||
IdleAccountCooldown Duration `yaml:"idleAccountCooldown"`
|
||||
IdleAccountCooldown Duration `yaml:"idleAccountCooldown"`
|
||||
MinEncryptedBytes int `yaml:"minEncryptedBytes"`
|
||||
EncryptedBytesPerReasoningToken int `yaml:"encryptedBytesPerReasoningToken"`
|
||||
}
|
||||
|
||||
type ClientKeyDefaultsConfig struct {
|
||||
@@ -809,6 +811,12 @@ func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) erro
|
||||
if d := value.IdleAccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) {
|
||||
return errors.New("qualityGuard.requestRetry.idleAccountCooldown 必须在 1m 到 168h 之间")
|
||||
}
|
||||
if value.MinEncryptedBytes != 0 && (value.MinEncryptedBytes < 64 || value.MinEncryptedBytes > 4096) {
|
||||
return errors.New("qualityGuard.requestRetry.minEncryptedBytes 必须在 64 到 4096 之间")
|
||||
}
|
||||
if value.EncryptedBytesPerReasoningToken != 0 && (value.EncryptedBytesPerReasoningToken < 1 || value.EncryptedBytesPerReasoningToken > 16) {
|
||||
return errors.New("qualityGuard.requestRetry.encryptedBytesPerReasoningToken 必须在 1 到 16 之间")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -944,6 +952,7 @@ func defaultConfig() Config {
|
||||
RequestRetry: QualityGuardRequestRetryConfig{
|
||||
MaxAttempts: 6, HoldTimeout: Duration(30 * time.Second), MinOutputTokens: 8, OnExhausted: "fail_closed",
|
||||
AccountCooldown: Duration(12 * time.Hour), IdleAccountCooldown: Duration(15 * time.Minute),
|
||||
MinEncryptedBytes: 256, EncryptedBytesPerReasoningToken: 4,
|
||||
},
|
||||
},
|
||||
ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent},
|
||||
|
||||
@@ -223,7 +223,7 @@ qualityGuard:
|
||||
func TestDefaultQualityGuardRequestRetryContract(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := defaultConfig().QualityGuard.RequestRetry
|
||||
if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute {
|
||||
if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute || got.MinEncryptedBytes != 256 || got.EncryptedBytesPerReasoningToken != 4 {
|
||||
t.Fatalf("requestRetry defaults = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -328,7 +325,11 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
if err := normalizeGzipResponse(resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, reqURL, reasoningRecovery := a.recoverReasoningDecodeFailure(ctx, request, accessToken, body, base, replayKey, resp, reqURL)
|
||||
var reasoningRecovery reasoningRecoveryOutcome
|
||||
resp, reqURL, reasoningRecovery, err = a.recoverReasoningDecodeFailure(ctx, request, accessToken, body, base, replayKey, resp, reqURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var recoveredPrimaryFailure *provider.DiagnosticResponse
|
||||
// Only eligible operations probe XAI with an equivalent request after the Build primary explicitly returns 403.
|
||||
if strings.EqualFold(base, primaryBase) && shouldProbeXAIInferenceFallback(request.Credential, request.Billing, request.Method, request.Path, resp.StatusCode) {
|
||||
@@ -352,7 +353,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
}
|
||||
fallbackRecovery := reasoningRecoveryOutcome{}
|
||||
if fallbackErr == nil {
|
||||
fallbackResp, fallbackURL, fallbackRecovery = a.recoverReasoningDecodeFailure(ctx, request, accessToken, fallbackBody, fallbackBase, fallbackReplayKey, fallbackResp, fallbackURL)
|
||||
fallbackResp, fallbackURL, fallbackRecovery, fallbackErr = a.recoverReasoningDecodeFailure(ctx, request, accessToken, fallbackBody, fallbackBase, fallbackReplayKey, fallbackResp, fallbackURL)
|
||||
}
|
||||
if fallbackErr == nil && isHTTPSuccess(fallbackResp.StatusCode) {
|
||||
recoveredPrimaryFailure = bufferedFailureDiagnostic(primaryResp, primaryBody, primaryTruncated)
|
||||
@@ -471,15 +472,15 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
if diagnostic == nil {
|
||||
return nil, convertErr
|
||||
}
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: reqURL, Diagnostic: diagnostic, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: reqURL, Diagnostic: diagnostic, ReasoningRecoveryFailed: reasoningRecovery.failed, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(converted))
|
||||
resp.Header.Set("Content-Length", strconv.Itoa(len(converted)))
|
||||
resp.Header.Set("Content-Type", "application/json")
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: diagnostic, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: diagnostic, ReasoningRecoveryFailed: reasoningRecovery.failed, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
}
|
||||
}
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: rateLimitDiagnostic, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: rateLimitDiagnostic, ReasoningRecoveryFailed: reasoningRecovery.failed, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) shouldCaptureReplay(request provider.ResponseResourceRequest, resp *http.Response, replayKey string) bool {
|
||||
|
||||
@@ -404,7 +404,7 @@ func TestNativeBuildHistoryItemsArePreservedAndSanitized(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningWithoutEncryptedContentRemainsNative(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"}},
|
||||
@@ -421,12 +421,12 @@ func TestReasoningWithoutEncryptedContentRemainsNative(t *testing.T) {
|
||||
}
|
||||
items := request["input"].([]any)
|
||||
first := items[0].(map[string]any)
|
||||
if first["type"] != "reasoning" || first["status"] != nil || first["encrypted_content"] != nil || first["content"] != nil {
|
||||
t.Fatalf("reasoning history = %#v", first)
|
||||
if first["type"] != "message" || first["role"] != "assistant" {
|
||||
t.Fatalf("unencrypted reasoning should become portable summary, got %#v", first)
|
||||
}
|
||||
summary := first["summary"].([]any)[0].(map[string]any)
|
||||
if summary["text"] != "who am I" {
|
||||
t.Fatalf("reasoning summary = %#v", first["summary"])
|
||||
text := first["content"].(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])
|
||||
|
||||
@@ -89,18 +89,18 @@ func (c *gatewayCompactionCodec) decode(session, blob string) (summary string, o
|
||||
// expandGatewayCompactionHistory restores gateway-owned remote-v2 state to a
|
||||
// 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) {
|
||||
// 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 {
|
||||
@@ -111,10 +111,11 @@ 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
|
||||
continue
|
||||
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
|
||||
@@ -126,11 +127,11 @@ func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec,
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,25 +309,34 @@ func TestUpstreamCompactionBlobIsForwarded(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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")
|
||||
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 != 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)
|
||||
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"
|
||||
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") {
|
||||
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
|
||||
@@ -310,13 +345,13 @@ func TestForwardResponseKeepsUpstreamCompactionBlob(t *testing.T) {
|
||||
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"}]}`),
|
||||
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 || strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "foreign_compaction_omitted") {
|
||||
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"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,31 +259,21 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin
|
||||
}
|
||||
|
||||
func sanitizeReasoningInput(item map[string]any) map[string]any {
|
||||
// 官方 Grok Build 回放 reasoning 时会删除 output-only status,但会保留
|
||||
// id、summary、content 和可选 encrypted_content。密文不是回放的前置条件。
|
||||
// Keep ciphertext-backed reasoning native. Summary-only items are rewritten
|
||||
// as assistant 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 !hasPortableReasoningContent(converted) {
|
||||
return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.")
|
||||
if portable, ok := portableReasoningSummaryMessage(converted); ok {
|
||||
return portable
|
||||
}
|
||||
return converted
|
||||
}
|
||||
|
||||
func hasPortableReasoningContent(item map[string]any) bool {
|
||||
if encrypted, ok := item["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" {
|
||||
return true
|
||||
}
|
||||
for _, key := range []string{"summary", "content"} {
|
||||
if values, ok := item[key].([]any); ok && len(values) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.")
|
||||
}
|
||||
|
||||
// sanitizeNativeHistoryInput rebuilds history from native Grok Build InputItem fields
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
var reasoningDecodeFailureMarkers = [][]byte{
|
||||
[]byte("could not decrypt the provided encrypted_content"),
|
||||
[]byte("invalid_encrypted_content"),
|
||||
}
|
||||
|
||||
var compactionBlobDecodeFailureMarkers = [][]byte{
|
||||
@@ -49,12 +50,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 assistant 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,
|
||||
@@ -64,18 +67,26 @@ func (a *Adapter) recoverReasoningDecodeFailure(
|
||||
replayKey string,
|
||||
response *http.Response,
|
||||
requestURL string,
|
||||
) (*http.Response, string, reasoningRecoveryOutcome) {
|
||||
) (*http.Response, string, reasoningRecoveryOutcome, error) {
|
||||
if response == nil || response.StatusCode != http.StatusBadRequest {
|
||||
return response, requestURL, reasoningRecoveryOutcome{}
|
||||
return response, requestURL, reasoningRecoveryOutcome{}, nil
|
||||
}
|
||||
errorBody, truncated, err := provider.ReadDiagnosticBody(response.Body)
|
||||
_ = response.Body.Close()
|
||||
if err != nil {
|
||||
return cloneBufferedResponse(response, errorBody, truncated), requestURL, reasoningRecoveryOutcome{}
|
||||
return cloneBufferedResponse(response, errorBody, truncated), requestURL, reasoningRecoveryOutcome{}, nil
|
||||
}
|
||||
original := cloneBufferedResponse(response, errorBody, truncated)
|
||||
if truncated || isCompactionBlobDecodeFailure(errorBody) || !isReasoningDecodeFailure(errorBody) {
|
||||
return original, requestURL, reasoningRecoveryOutcome{}
|
||||
if truncated || !isReasoningDecodeFailure(errorBody) {
|
||||
return original, requestURL, 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 original, requestURL, reasoningRecoveryOutcome{}, nil
|
||||
}
|
||||
// 一旦上游明确拒绝 opaque reasoning,立即清理该账号/平面的服务端回放,
|
||||
// 防止下次请求再次注入同一份已失效密文。成功响应会按正常 Capture 流程写回新状态。
|
||||
@@ -88,71 +99,73 @@ func (a *Adapter) recoverReasoningDecodeFailure(
|
||||
retry, retryURL, retryErr := a.retryReasoningRecovery(ctx, request, accessToken, portableBody, base, false)
|
||||
if retryErr != nil {
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "transport_failed", 0, retryErr)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
_ = original.Body.Close()
|
||||
return nil, requestURL, reasoningRecoveryOutcome{}, retryErr
|
||||
}
|
||||
if err := normalizeGzipResponse(retry); err != nil {
|
||||
_ = retry.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "response_decode_failed", retry.StatusCode, err)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
}
|
||||
if isHTTPSuccess(retry.StatusCode) {
|
||||
_ = original.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "recovered", retry.StatusCode, nil)
|
||||
return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}
|
||||
return nil, retryURL, reasoningRecoveryOutcome{}, err
|
||||
}
|
||||
if retry.StatusCode == http.StatusTooManyRequests {
|
||||
// 去除失效密文后得到的 429 是当前账号的真实上游状态。保留它,
|
||||
// 让网关进行账号冷却和切换,不能回退成已无效的初始解码 400。
|
||||
if retry.StatusCode != http.StatusBadRequest {
|
||||
_ = original.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "rate_limited", retry.StatusCode, nil)
|
||||
return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}
|
||||
result := "retry_response"
|
||||
if isHTTPSuccess(retry.StatusCode) {
|
||||
result = "recovered"
|
||||
}
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", result, retry.StatusCode, nil)
|
||||
return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}, nil
|
||||
}
|
||||
retryStatus := retry.StatusCode
|
||||
sameDecodeFailure, inspectErr := responseHasReasoningDecodeFailure(retry)
|
||||
if inspectErr != nil || !sameDecodeFailure {
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retry.StatusCode, inspectErr)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
if inspectErr != nil {
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, inspectErr)
|
||||
_ = original.Body.Close()
|
||||
return nil, retryURL, reasoningRecoveryOutcome{}, inspectErr
|
||||
}
|
||||
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)
|
||||
}
|
||||
a.logReasoningRecovery(request, base, "encrypted_content", "decode_error_persisted", retry.StatusCode, nil)
|
||||
}
|
||||
|
||||
if !canResetReasoningSession(request, portableBody) {
|
||||
a.logReasoningRecovery(request, base, "session_reset", "not_safe", 0, nil)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}, nil
|
||||
}
|
||||
statelessBody := removePromptCacheKey(portableBody)
|
||||
retry, retryURL, retryErr := a.retryReasoningRecovery(ctx, request, accessToken, statelessBody, base, true)
|
||||
if retryErr != nil {
|
||||
a.logReasoningRecovery(request, base, "session_reset", "transport_failed", 0, retryErr)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
_ = original.Body.Close()
|
||||
return nil, requestURL, reasoningRecoveryOutcome{}, retryErr
|
||||
}
|
||||
if err := normalizeGzipResponse(retry); err != nil {
|
||||
_ = retry.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "session_reset", "response_decode_failed", retry.StatusCode, err)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
}
|
||||
if retry.StatusCode == http.StatusTooManyRequests {
|
||||
// 无状态恢复也可能命中当前账号的真实限流。与去密文恢复保持一致,
|
||||
// 必须把 429 交回网关,才能执行账号冷却和候选账号切换。
|
||||
_ = original.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "session_reset", "rate_limited", retry.StatusCode, nil)
|
||||
return nil, retryURL, reasoningRecoveryOutcome{}, err
|
||||
}
|
||||
if retry.StatusCode != http.StatusBadRequest {
|
||||
_ = original.Body.Close()
|
||||
result := "retry_response"
|
||||
if isHTTPSuccess(retry.StatusCode) {
|
||||
result = "recovered"
|
||||
}
|
||||
a.logReasoningRecovery(request, base, "session_reset", result, retry.StatusCode, nil)
|
||||
return retry, retryURL, reasoningRecoveryOutcome{
|
||||
encryptedContentDowngraded: encryptedChanged,
|
||||
sessionReset: true,
|
||||
}
|
||||
}
|
||||
if !isHTTPSuccess(retry.StatusCode) {
|
||||
status := retry.StatusCode
|
||||
_ = retry.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "session_reset", "retry_rejected", status, nil)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}
|
||||
}, nil
|
||||
}
|
||||
|
||||
_ = original.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "session_reset", "recovered", retry.StatusCode, nil)
|
||||
return retry, retryURL, reasoningRecoveryOutcome{
|
||||
encryptedContentDowngraded: encryptedChanged,
|
||||
sessionReset: true,
|
||||
}
|
||||
_ = retry.Body.Close()
|
||||
a.logReasoningRecovery(request, base, "session_reset", "retry_rejected", retry.StatusCode, nil)
|
||||
return original, requestURL, reasoningRecoveryOutcome{failed: true}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) retryReasoningRecovery(ctx context.Context, request provider.ResponseResourceRequest, accessToken string, body []byte, base string, resetSession bool) (*http.Response, string, error) {
|
||||
@@ -233,7 +246,7 @@ func (a *Adapter) logReasoningRecovery(request provider.ResponseResourceRequest,
|
||||
}
|
||||
|
||||
func isReasoningDecodeFailure(body []byte) bool {
|
||||
return containsDecodeFailureMarker(body, reasoningDecodeFailureMarkers)
|
||||
return isCompactionBlobDecodeFailure(body) || containsDecodeFailureMarker(body, reasoningDecodeFailureMarkers)
|
||||
}
|
||||
|
||||
func isCompactionBlobDecodeFailure(body []byte) bool {
|
||||
@@ -250,9 +263,27 @@ func containsDecodeFailureMarker(body []byte, markers [][]byte) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// stripReasoningEncryptedContent removes opaque reasoning state while
|
||||
// preserving any readable summary/content. An encrypted-only reasoning item
|
||||
// becomes empty after stripping and is removed entirely.
|
||||
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. 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 {
|
||||
@@ -266,23 +297,28 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
|
||||
rebuilt := make([]any, 0, len(input))
|
||||
for _, raw := range input {
|
||||
item, ok := raw.(map[string]any)
|
||||
if !ok || stringField(item, "type") != "reasoning" {
|
||||
if !ok {
|
||||
rebuilt = append(rebuilt, raw)
|
||||
continue
|
||||
}
|
||||
encrypted, ok := item["encrypted_content"].(string)
|
||||
if !ok || strings.TrimSpace(encrypted) == "" {
|
||||
rebuilt = append(rebuilt, raw)
|
||||
if stringField(item, "type") == "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
|
||||
if portable, ok := portableReasoningSummaryMessage(item); ok {
|
||||
rebuilt = append(rebuilt, portable)
|
||||
}
|
||||
continue
|
||||
}
|
||||
cleaned := cloneJSONObject(item)
|
||||
delete(cleaned, "encrypted_content")
|
||||
delete(cleaned, "id")
|
||||
delete(cleaned, "status")
|
||||
changed = true
|
||||
if hasReadableReasoningContent(cleaned) {
|
||||
rebuilt = append(rebuilt, cleaned)
|
||||
}
|
||||
rebuilt = append(rebuilt, raw)
|
||||
}
|
||||
if !changed {
|
||||
return body, false
|
||||
@@ -295,17 +331,29 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) {
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
func hasReadableReasoningContent(item map[string]any) bool {
|
||||
func portableReasoningSummaryMessage(item map[string]any) (map[string]any, bool) {
|
||||
text := reasoningPortableText(item)
|
||||
if text == "" {
|
||||
return nil, false
|
||||
}
|
||||
return map[string]any{
|
||||
"type": "message", "role": "assistant",
|
||||
"content": "Prior model reasoning summary:\n" + text,
|
||||
}, true
|
||||
}
|
||||
|
||||
func reasoningPortableText(item map[string]any) string {
|
||||
var parts []string
|
||||
for _, field := range []string{"summary", "content"} {
|
||||
parts, _ := item[field].([]any)
|
||||
for _, raw := range parts {
|
||||
values, _ := item[field].([]any)
|
||||
for _, raw := range values {
|
||||
part, _ := raw.(map[string]any)
|
||||
if strings.TrimSpace(stringField(part, "text")) != "" {
|
||||
return true
|
||||
if text := strings.TrimSpace(stringField(part, "text")); text != "" {
|
||||
parts = append(parts, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
return strings.Join(parts, "\n")
|
||||
}
|
||||
|
||||
func appendCompatibilityWarning(header http.Header, warning string) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -22,6 +23,7 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T
|
||||
{"type":"reasoning","id":"rs_empty","status":"completed","summary":[],"encrypted_content":"opaque-empty"},
|
||||
{"type":"reasoning","summary":[{"type":"summary_text","text":""}],"encrypted_content":"opaque-blank"},
|
||||
{"type":"reasoning","id":"rs_summary","status":"completed","summary":[{"type":"summary_text","text":"readable"}],"encrypted_content":"opaque-summary"},
|
||||
{"type":"compaction","id":"cmp_1","encrypted_content":"opaque-compaction"},
|
||||
{"type":"message","role":"assistant","content":"answer","encrypted_content":"message-value"},
|
||||
{"type":"message","role":"user","content":"continue"}
|
||||
]
|
||||
@@ -33,15 +35,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 {
|
||||
t.Fatalf("downgraded = %s", downgraded)
|
||||
if json.Unmarshal(downgraded, &payload) != nil || len(payload.Input) != 4 {
|
||||
t.Fatalf("downgraded = %s, len=%d", downgraded, len(payload.Input))
|
||||
}
|
||||
reasoning := payload.Input[0]
|
||||
if reasoning["type"] != "reasoning" || reasoning["id"] != nil || reasoning["status"] != nil || reasoning["encrypted_content"] != nil {
|
||||
t.Fatalf("reasoning = %#v", reasoning)
|
||||
summary := payload.Input[0]
|
||||
if summary["type"] != "message" || summary["role"] != "assistant" {
|
||||
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"].(string)
|
||||
if !strings.Contains(summaryText, "readable") || strings.Contains(summaryText, "omitted") {
|
||||
t.Fatalf("readable reasoning text = %q", summaryText)
|
||||
}
|
||||
compaction := payload.Input[1]
|
||||
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])
|
||||
}
|
||||
if payload.Input[3]["role"] != "user" {
|
||||
t.Fatalf("user message changed: %#v", payload.Input[3])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +152,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 decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
|
||||
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
|
||||
case 3:
|
||||
data, _ := io.ReadAll(request.Body)
|
||||
if request.URL.Host != "xai.test" || strings.Contains(string(data), `"type":"reasoning"`) {
|
||||
@@ -168,6 +181,50 @@ func TestRecoverReasoningDecodeFailureStaysOnXAIFallbackPlane(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverReasoningDecodeFailureLetsRecoveredForbiddenReachPlaneFallback(t *testing.T) {
|
||||
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
|
||||
adapter.SetFallbackMarker(reasoningRecoveryFallbackMarker{})
|
||||
var calls atomic.Int32
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
switch call := calls.Add(1); call {
|
||||
case 1:
|
||||
if request.URL.Host != "build.test" {
|
||||
t.Fatalf("primary host = %q", request.URL.Host)
|
||||
}
|
||||
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 request.URL.Host != "build.test" || strings.Contains(string(data), `"encrypted_content"`) {
|
||||
t.Fatalf("portable retry host=%q body=%s", request.URL.Host, data)
|
||||
}
|
||||
return jsonHTTPResponse(request, http.StatusForbidden, `{"error":"build denied"}`), nil
|
||||
case 3:
|
||||
if request.URL.Host != "xai.test" {
|
||||
t.Fatalf("fallback host = %q", request.URL.Host)
|
||||
}
|
||||
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,
|
||||
BuildRouteMode: account.BuildRouteAuto, BuildSuperEntitled: true,
|
||||
},
|
||||
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5",
|
||||
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()
|
||||
if calls.Load() != 3 || response.StatusCode != http.StatusOK || response.RecoveredPrimaryFailure == nil || response.RecoveredPrimaryFailure.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("calls=%d status=%d recovered_primary=%#v", calls.Load(), response.StatusCode, response.RecoveredPrimaryFailure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverReasoningDecodeFailureResetsSessionWithoutOpaqueInput(t *testing.T) {
|
||||
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
|
||||
var calls atomic.Int32
|
||||
@@ -179,7 +236,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 decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
|
||||
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), 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 +285,7 @@ func TestRecoverReasoningDecodeFailureEscalatesFromOpaqueStripToSessionReset(t *
|
||||
default:
|
||||
t.Fatalf("unexpected call %d", call)
|
||||
}
|
||||
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
|
||||
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},
|
||||
@@ -251,7 +308,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 decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
|
||||
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
|
||||
case 2:
|
||||
data, _ := io.ReadAll(request.Body)
|
||||
if strings.Contains(string(data), `"encrypted_content"`) {
|
||||
@@ -306,7 +363,7 @@ func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterSessionReset(t *tes
|
||||
t.Fatalf("unexpected call %d", call)
|
||||
return nil, nil
|
||||
}
|
||||
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
|
||||
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{
|
||||
@@ -328,6 +385,101 @@ func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterSessionReset(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverReasoningDecodeFailurePreservesServerErrorAfterSessionReset(t *testing.T) {
|
||||
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
|
||||
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.StatusBadGateway, `{"error":"stateless retry failed upstream"}`), 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":[{"role":"user","content":"continue"}]}`),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
|
||||
if calls.Load() != 2 || response.StatusCode != http.StatusBadGateway || !strings.Contains(string(body), "stateless retry failed upstream") {
|
||||
t.Fatalf("calls=%d status=%d body=%s", calls.Load(), response.StatusCode, body)
|
||||
}
|
||||
if response.ReasoningRecoveryFailed || !strings.Contains(warnings, "reasoning_session_reset") || strings.Contains(warnings, "reasoning_recovery_failed") {
|
||||
t.Fatalf("internal_failure=%t warnings=%q", response.ReasoningRecoveryFailed, warnings)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
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": opaqueReasoning,
|
||||
},
|
||||
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)
|
||||
}
|
||||
switch call {
|
||||
case 1:
|
||||
if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) {
|
||||
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 reasoning:size=%d", len(data))
|
||||
}
|
||||
return jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited after reasoning recovery"}}`), 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: "million-token-session",
|
||||
Body: body,
|
||||
})
|
||||
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() != 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.
|
||||
@@ -335,7 +487,8 @@ 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",
|
||||
"model": "grok-4.5",
|
||||
"previous_response_id": "resp_compacted",
|
||||
"input": []any{
|
||||
map[string]any{
|
||||
"type": "compaction",
|
||||
@@ -357,7 +510,7 @@ func TestCompactionBlobDecodeFailureIsReturnedToClient(t *testing.T) {
|
||||
if call != 1 {
|
||||
t.Fatalf("unexpected recovery retry %d", call)
|
||||
}
|
||||
if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) {
|
||||
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
|
||||
@@ -388,7 +541,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 decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil
|
||||
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},
|
||||
@@ -402,29 +555,59 @@ func TestRecoverReasoningDecodeFailureDoesNotResetStoredResponseChain(t *testing
|
||||
if calls.Load() != 1 || response.StatusCode != http.StatusBadRequest || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") {
|
||||
t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), response.StatusCode, response.Header.Get("X-Grok2API-Compatibility-Warnings"))
|
||||
}
|
||||
if !response.ReasoningRecoveryFailed {
|
||||
t.Fatal("exhausted same-account recovery must set the internal gateway retry hint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverReasoningDecodeFailurePreservesOriginalWhenRetryFails(t *testing.T) {
|
||||
func TestRecoverReasoningDecodeFailureReturnsNon400RetryResponse(t *testing.T) {
|
||||
for _, status := range []int{http.StatusUnauthorized, http.StatusServiceUnavailable} {
|
||||
t.Run(http.StatusText(status), func(t *testing.T) {
|
||||
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
|
||||
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, status, `{"error":"recovery retry 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",
|
||||
Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"}]}`),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, _ := io.ReadAll(response.Body)
|
||||
if calls.Load() != 2 || response.StatusCode != status || !strings.Contains(string(data), "recovery retry response") {
|
||||
t.Fatalf("calls=%d status=%d headers=%#v body=%s", calls.Load(), response.StatusCode, response.Header, data)
|
||||
}
|
||||
if response.ReasoningRecoveryFailed || strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") {
|
||||
t.Fatalf("non-400 retry was mislabeled as recovery failure: %#v", response)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverReasoningDecodeFailurePropagatesRetryTransportError(t *testing.T) {
|
||||
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
|
||||
wantErr := errors.New("recovery transport failed")
|
||||
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 decrypt the provided encrypted_content. Ensure the value is unmodified."}`), 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.StatusServiceUnavailable, `{"error":"temporary failure"}`), nil
|
||||
return nil, wantErr
|
||||
})
|
||||
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",
|
||||
Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"}]}`),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, _ := io.ReadAll(response.Body)
|
||||
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)
|
||||
if response != nil || !errors.Is(err, wantErr) || calls.Load() != 2 {
|
||||
t.Fatalf("response=%#v err=%v calls=%d", response, err, calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,3 +641,102 @@ type reasoningRecoveryFallbackMarker struct{}
|
||||
func (reasoningRecoveryFallbackMarker) MarkBuildAPIFallback(context.Context, uint64, bool) error {
|
||||
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 TestRecoverReasoningDecodeFailureKeepsLegacyCompactionMarkerWithoutCompactionInput(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)
|
||||
if call == 1 {
|
||||
return jsonHTTPResponse(request, http.StatusBadRequest, `{"code":"invalid-argument","error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
|
||||
}
|
||||
return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil
|
||||
})
|
||||
|
||||
body := []byte(`{"model":"grok-4.6","messages":[{"role":"user","content":"hello"}]}`)
|
||||
resp, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
|
||||
Credential: account.Credential{ID: 131, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
|
||||
Method: http.MethodPost, Path: "/responses", Model: "grok-4.6", PromptCacheKey: "session-compaction-test",
|
||||
NormalizeBody: true, Operation: conversation.OperationChat, Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
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"))
|
||||
}
|
||||
}
|
||||
@@ -944,7 +944,7 @@ func TestConvertResponsesStreamMarksEncryptedChatReasoningEvidence(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(converted)
|
||||
if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 || strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 {
|
||||
if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 || strings.Count(text, ": grok2api-reasoning-evidence 9\n\n") != 1 {
|
||||
t.Fatalf("encrypted reasoning markers missing or duplicated: %s", text)
|
||||
}
|
||||
if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") {
|
||||
@@ -964,7 +964,7 @@ func TestConvertResponsesStreamMarksFinalEnvelopeReasoningEvidence(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(converted)
|
||||
if strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 {
|
||||
if strings.Count(text, ": grok2api-reasoning-evidence 9\n\n") != 1 {
|
||||
t.Fatalf("final-envelope reasoning evidence missing or duplicated: %s", text)
|
||||
}
|
||||
if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") {
|
||||
|
||||
@@ -52,36 +52,36 @@ func ConvertResponseStreamWithOptions(source io.ReadCloser, operation string, op
|
||||
}
|
||||
|
||||
type streamConverter struct {
|
||||
writer io.Writer
|
||||
operation string
|
||||
id string
|
||||
model string
|
||||
created int64
|
||||
started bool
|
||||
finished bool
|
||||
textStarted bool
|
||||
textIndex int
|
||||
thinkingStarted bool
|
||||
thinkingClosed bool
|
||||
thinkingIndex int
|
||||
thinkingItemID string
|
||||
chatReasoningMark bool
|
||||
evidenceMarked bool
|
||||
reasoningItems map[string]*reasoningStreamState
|
||||
reasoningOrder []string
|
||||
activeReasoningID string
|
||||
nextIndex int
|
||||
tools map[string]streamTool
|
||||
webSearch []webSearchCall
|
||||
webSearchEmitted map[string]bool
|
||||
deferSearchText bool
|
||||
pendingSearchText strings.Builder
|
||||
usage responseUsage
|
||||
options ResponseOptions
|
||||
stopFilter *anthropicStreamStopFilter
|
||||
stopSequence string
|
||||
refused bool
|
||||
repeatTracker streamRepeatTracker
|
||||
writer io.Writer
|
||||
operation string
|
||||
id string
|
||||
model string
|
||||
created int64
|
||||
started bool
|
||||
finished bool
|
||||
textStarted bool
|
||||
textIndex int
|
||||
thinkingStarted bool
|
||||
thinkingClosed bool
|
||||
thinkingIndex int
|
||||
thinkingItemID string
|
||||
chatReasoningMark bool
|
||||
reasoningEvidenceBytes int
|
||||
reasoningItems map[string]*reasoningStreamState
|
||||
reasoningOrder []string
|
||||
activeReasoningID string
|
||||
nextIndex int
|
||||
tools map[string]streamTool
|
||||
webSearch []webSearchCall
|
||||
webSearchEmitted map[string]bool
|
||||
deferSearchText bool
|
||||
pendingSearchText strings.Builder
|
||||
usage responseUsage
|
||||
options ResponseOptions
|
||||
stopFilter *anthropicStreamStopFilter
|
||||
stopSequence string
|
||||
refused bool
|
||||
repeatTracker streamRepeatTracker
|
||||
}
|
||||
|
||||
// streamRepeatTracker 在协议转换、缓冲和 stop filter 之前跟踪上游增量,
|
||||
@@ -148,20 +148,21 @@ func newStreamConverter(writer io.Writer, operation string, options ResponseOpti
|
||||
}
|
||||
}
|
||||
|
||||
// markReasoningEvidence preserves non-empty upstream encrypted_content for the
|
||||
// request-path quality scanner after protocol conversion. SSE clients ignore
|
||||
// comments, so Chat and Messages public event payloads remain unchanged.
|
||||
func (c *streamConverter) markReasoningEvidence() error {
|
||||
if c.evidenceMarked {
|
||||
// markReasoningEvidence preserves the upstream encrypted_content byte length
|
||||
// for the request-path quality scanner after protocol conversion. SSE clients
|
||||
// ignore comments, so Chat and Messages public event payloads remain unchanged.
|
||||
func (c *streamConverter) markReasoningEvidence(encrypted string) error {
|
||||
byteCount := len(strings.TrimSpace(encrypted))
|
||||
if byteCount <= c.reasoningEvidenceBytes {
|
||||
return nil
|
||||
}
|
||||
if err := c.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.WriteString(c.writer, ": grok2api-reasoning-evidence\n\n"); err != nil {
|
||||
if _, err := fmt.Fprintf(c.writer, ": grok2api-reasoning-evidence %d\n\n", byteCount); err != nil {
|
||||
return err
|
||||
}
|
||||
c.evidenceMarked = true
|
||||
c.reasoningEvidenceBytes = byteCount
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -381,7 +382,7 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(item.Encrypted) != "" {
|
||||
if err := c.markReasoningEvidence(); err != nil {
|
||||
if err := c.markReasoningEvidence(item.Encrypted); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -398,7 +399,7 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
c.setResponse(response)
|
||||
for _, item := range response.Output {
|
||||
if item.Type == "reasoning" && strings.TrimSpace(item.Encrypted) != "" {
|
||||
if err := c.markReasoningEvidence(); err != nil {
|
||||
if err := c.markReasoningEvidence(item.Encrypted); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,6 +385,10 @@ type Response struct {
|
||||
QuotaUnits int
|
||||
UpstreamURL string
|
||||
Diagnostic *DiagnosticResponse
|
||||
// ReasoningRecoveryFailed is an internal retry hint emitted only after the Build
|
||||
// adapter exhausts same-account recovery for an opaque reasoning 400. Gateway
|
||||
// policy must not infer this state from an upstream-controlled response header.
|
||||
ReasoningRecoveryFailed bool
|
||||
// RecoveredPrimaryFailure records a primary-plane failure hidden by a successful Provider fallback.
|
||||
RecoveredPrimaryFailure *DiagnosticResponse
|
||||
RateLimit *RateLimitMetadata
|
||||
|
||||
+17
-9
@@ -150,16 +150,22 @@ qualityGuard:
|
||||
nodeIDs: []
|
||||
rotatableNodeIDs: []
|
||||
# Optional request-path withhold/retry for thinking models.
|
||||
# Observe up to 30s for real reasoning evidence. If upstream has announced
|
||||
# a reasoning item and visible output but proof arrives later, the still-open
|
||||
# stream is released at the deadline without penalizing the account. Empty or
|
||||
# terminal no-thinking responses are still retried.
|
||||
# Missing thinking with enough visible output is not delivered; another
|
||||
# account is tried (up to maxAttempts). fail_closed returns 503 instead
|
||||
# of the last body. Sidecar qualityGuard.enabled stays false until you
|
||||
# start the quality-guard profile.
|
||||
# Recommended lab values are filled in; enabled stays false so stock
|
||||
# installs do not intercept. Set enabled: true to turn the hold on.
|
||||
# Observe up to 30s for real reasoning evidence. A reasoning-item stub plus
|
||||
# enough visible output at the deadline is withheld (TUI dump after 30s),
|
||||
# not released as late ciphertext. Empty stub-only streams keep waiting.
|
||||
# Floor-met ciphertext that then dumps a short greeting in under 1s is
|
||||
# also withheld. TUI follow-ups (previous_response_id) and hosted tools
|
||||
# stay held for classification, but a quality withhold never replays
|
||||
# account-bound state or side-effecting tools. Context compaction stays exempt.
|
||||
# Replay-safe missing-thinking requests try another account (up to
|
||||
# maxAttempts). fail_closed returns 503 instead of the held body. Sidecar
|
||||
# qualityGuard.enabled stays false until you start the quality-guard profile.
|
||||
# Non-empty encrypted_content stubs are not thinking. The ciphertext floor
|
||||
# is max(minEncryptedBytes, reasoning_tokens * encryptedBytesPerReasoningToken).
|
||||
requestRetry:
|
||||
enabled: true
|
||||
enabled: false
|
||||
maxAttempts: 6
|
||||
holdTimeout: 30s
|
||||
minOutputTokens: 8
|
||||
@@ -171,3 +177,5 @@ qualityGuard:
|
||||
# Single-account pools should set this lower; toggling enabled does not
|
||||
# clear cooldown — use POST /api/admin/v1/accounts/:id/clear-cooldown.
|
||||
idleAccountCooldown: 15m
|
||||
minEncryptedBytes: 256
|
||||
encryptedBytesPerReasoningToken: 4
|
||||
Reference in new issue
Block a user