@@ -377,6 +378,9 @@ function StateBadge({ node, state, protectedNode }: { node: EgressNodeDTO; state
if (state?.disabled_by_guard) return
{t("qualityGuard.quarantined")};
if (protectedNode) return
{t("qualityGuard.fixedFallback")};
if (!node.enabled) return
{t("common.disabled")};
+ if (state?.quarantined_lease_count) return
{t("qualityGuard.leaseQuarantined", { count: state.quarantined_lease_count })};
+ if (state?.observe_only) return
{t("qualityGuard.leaseScopedObserveOnly")};
+ if (node.accountBoundProxy) return
{t("qualityGuard.leaseScoped")};
if (state?.error_strikes) return
{t("qualityGuard.probeFailed")};
if (state?.last_classification === "hard" || state?.last_classification === "soft") return
{t("qualityGuard.suspect")};
if (state?.last_classification === "healthy") return
{t("qualityGuard.healthy")};
@@ -389,13 +393,29 @@ function EventList({ events, locale }: { events: QualityGuardEvent[]; locale: st
{t("qualityGuard.events")}
{events.length === 0 ?
{t("qualityGuard.noEvents")}
:
{[...events].reverse().slice(0, 10).map((event, index) =>
-
{event.node_name || `ID ${event.node_id}`} · {t(`qualityGuard.eventTypes.${event.event}`)}
{t(`qualityGuard.reasons.${event.reason || "unknown"}`)}{event.output_tps ? ` · ${formatTPS(event.output_tps)}` : ""}
+
{event.node_name || `ID ${event.node_id}`} · {t(eventLabelKey(event.event))}
{t(reasonLabelKey(event.reason))}{event.account_id ? ` · ${t("qualityGuard.accountLease", { id: event.account_id })}` : ""}{event.request_id ? ` · ${event.request_id}` : ""}{event.cooldown_until ? ` · ${t("qualityGuard.leaseUntil", { time: formatTime(event.cooldown_until, locale) })}` : ""}{event.output_tps ? ` · ${formatTPS(event.output_tps)}` : ""}
)}
}
;
}
+function eventLabelKey(event: string): string {
+ if (event === "lease_scoped_quarantine_suppressed") return "qualityGuard.leaseScopedQuarantineSuppressedEvent";
+ if (event === "lease_scoped_guard_released") return "qualityGuard.leaseScopedGuardReleasedEvent";
+ if (event === "lease_quarantined") return "qualityGuard.leaseQuarantinedEvent";
+ if (event === "lease_restored") return "qualityGuard.leaseRestoredEvent";
+ if (event === "lease_quarantine_extended") return "qualityGuard.leaseQuarantineExtendedEvent";
+ if (event === "lease_quarantine_failed" || event === "lease_quarantine_suppressed") return "qualityGuard.leaseQuarantineFailedEvent";
+ return `qualityGuard.eventTypes.${event}`;
+}
+
+function reasonLabelKey(reason: string): string {
+ if (reason === "lease_scoped_node") return "qualityGuard.leaseScopedNodeReason";
+ if (reason === "fixed_fallback_node") return "qualityGuard.fixedFallback";
+ return `qualityGuard.reasons.${reason || "unknown"}`;
+}
+
function Policy({ status, onEdit }: { status: QualityGuardStatus; onEdit: () => void }) {
const { t } = useTranslation();
const config = status.config;
@@ -535,6 +555,7 @@ function qualityTestState(result: QualityTestResult, status: QualityGuardStatus)
else if (result.outputTokensPerSecond >= softTPS) { classification = "soft"; reason = "soft_tps"; }
const now = Date.now() / 1000;
return {
+ observe_only: false, observe_only_reason: "", quarantined_lease_count: 0,
active_soft_strikes: classification === "soft" ? 1 : classification === "hard" ? (status.config?.consecutive_soft ?? 2) : 0,
passive_soft_strikes: 0, error_strikes: 0, quarantined_until: 0, disabled_by_guard: false,
last_reason: reason, last_probe_at: now, last_observed_at: now, last_source: "active",
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts
index 8dea5ba8..f1e07eee 100644
--- a/frontend/src/shared/i18n/index.ts
+++ b/frontend/src/shared/i18n/index.ts
@@ -471,17 +471,32 @@ const resources = {
},
qualityGuard: {
title: "质量守护", description: "监测 Grok 出口质量并在异常时自动隔离节点。", overview: "质量守护概览",
- serviceStatus: "守护服务", running: "运行正常", stale: "状态滞后", mode: "检测模式", availableNodes: "已启用节点", quarantinedNodes: "已隔离节点",
+ serviceStatus: "守护服务", running: "运行正常", stale: "状态滞后", mode: "检测模式", availableNodes: "已启用节点", quarantinedNodes: "已隔离节点", quarantinedTargets: "隔离对象",
modes: { active: "主动检测", passive: "被动审计", hybrid: "混合模式" },
nodes: "节点质量", nodesHelp: "速度与 grok2api 面板同口径:输出 Token 包含推理 Token。首字后窗口短于首字等待且不足 1 秒时改用全程,避免加密思考被挤进最后几十毫秒。完整用户请求出现速度异常后会立即隔离,并在隔离期结束后使用受控探针复测。", updatedAt: "状态更新于 {{time}}",
node: "节点", state: "状态", outputTPS: "面板输出速度", firstToken: "首字延迟", source: "数据来源", strikes: "打击计数", lastObserved: "最近观测", test: "检测",
sources: { active: "主动探针", passive: "请求审计" }, quarantined: "已隔离", fixedFallback: "固定回退(受保护)", suspect: "可疑", healthy: "正常", pending: "待观测", probeFailed: "检测失败",
- events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求" },
+ events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求", lease_quarantined: "账号租约已隔离", lease_restored: "账号租约已恢复", lease_quarantine_extended: "账号租约隔离已延长", lease_quarantine_failed: "账号租约隔离未执行" },
statistics: "自动检测统计", statisticsSince: "自 {{time}} 开始累计,不含手动检测。", statisticsChecks: "有效检测总数", statisticsChecksHelp: "主动探测与有效被动审计", statisticsActive: "主动探测", statisticsActiveDetail: "正常 {{healthy}},错误 {{errors}}", statisticsPassive: "被动审计", statisticsPassiveDetail: "正常 {{healthy}},来自真实请求", statisticsTokens: "主动探测输出 Token", statisticsTokensHelp: "包含推理 Token,不代表代理流量", statisticsAnomalies: "异常命中", statisticsAnomalyDetail: "软异常 {{soft}},硬异常 {{hard}}", statisticsQuarantines: "执行隔离", statisticsActionDetail: "已恢复 {{restored}},受保护未隔离 {{suppressed}}",
reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", missing_thinking: "输出缺少 thinking", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" },
policy: "当前策略", editPolicy: "编辑策略", editPolicyTitle: "编辑质量守护策略", editPolicyDescription: "保存后由守护进程热加载,无需重启服务。", restoreDefaults: "恢复默认值", policySaved: "策略已保存,正在热加载", invalidPolicyValue: "数值超出允许范围", softThresholdMustBeLower: "软阈值必须低于硬阈值", activeIntervalSeconds: "主动检测间隔(秒)", passiveIntervalSeconds: "被动审计间隔(秒)", consecutiveSoft: "主动软异常连续次数", consecutiveErrors: "检测错误连续次数", quarantineSeconds: "隔离时长(秒)", softThreshold: "软阈值", hardThreshold: "硬阈值", activeInterval: "主动间隔", passiveInterval: "审计间隔", quarantineDuration: "隔离时长", minimumNodes: "最少保留节点",
unavailable: "质量守护尚未连接", unavailableHelp: "在 config.yaml 中启用 qualityGuard,并启动 quality-guard Compose profile 后,这里会显示实时状态。", testing: "正在检测节点质量", testComplete: "检测完成:{{speed}}", testFailed: "质量检测暂不可用,请稍后重试",
nodesTab: "节点质量",
+ leaseScopedObserveOnly: "租约级(仅观测)",
+ leaseScoped: "租约级",
+ leaseQuarantined: "租约隔离 {{count}}",
+ leaseScopedHelp: "该节点按账号生成不同粘性租约;异常请求只隔离对应账号租约,不会停用整个共享节点。",
+ leaseScopedObserveOnlyHelp: "当前异常缺少账号身份或租约接口不可用,因此仅记录观测,不会停用整个共享节点。",
+ leaseQuarantinedEvent: "账号租约已隔离",
+ leaseRestoredEvent: "账号租约已恢复",
+ leaseQuarantineExtendedEvent: "账号租约隔离已延长",
+ leaseQuarantineFailedEvent: "账号租约隔离未执行",
+ leaseScopedQuarantineSuppressedEvent: "已阻止整节点隔离",
+ leaseScopedGuardReleasedEvent: "已解除旧版整节点隔离",
+ leaseScopedNodeReason: "节点包含多个账号粘性租约",
+ accountLease: "账号 {{id}}",
+ leaseUntil: "隔离至 {{time}}",
+ statisticsSuppressedActionDetail: "已恢复 {{restored}},策略抑制 {{suppressed}}",
profilesTab: "探针方案",
profilesHelp: "主动质量探测用的 Prompt 与预期标记。标记缺失记为硬异常。",
profileActive: "当前使用",
@@ -1557,6 +1572,22 @@ const resources = {
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. A tail shorter than the first-token wait and under 1s uses the full request duration so encrypted thinking is not crushed into the flush. A completed user request with anomalous throughput is isolated immediately, then verified with a controlled probe after the hold.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", missing_thinking: "Missing thinking tokens", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Request exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive active soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.",
nodesTab: "Node quality",
+ quarantinedTargets: "Quarantined targets",
+ leaseScopedObserveOnly: "Lease-scoped (observe only)",
+ leaseScoped: "Lease-scoped",
+ leaseQuarantined: "{{count}} lease quarantined",
+ leaseScopedHelp: "This node renders a different sticky lease per account. An anomalous request quarantines only that account lease, never the shared node.",
+ leaseScopedObserveOnlyHelp: "The anomaly lacks an account identity or the lease API is unavailable, so it is observed without disabling the shared node.",
+ leaseQuarantinedEvent: "Account lease quarantined",
+ leaseRestoredEvent: "Account lease restored",
+ leaseQuarantineExtendedEvent: "Account lease quarantine extended",
+ leaseQuarantineFailedEvent: "Account lease quarantine not applied",
+ leaseScopedQuarantineSuppressedEvent: "Whole-node quarantine prevented",
+ leaseScopedGuardReleasedEvent: "Legacy whole-node quarantine released",
+ leaseScopedNodeReason: "Node contains multiple account-specific sticky leases",
+ accountLease: "Account {{id}}",
+ leaseUntil: "Quarantined until {{time}}",
+ statisticsSuppressedActionDetail: "Restored {{restored}}, suppressed {{suppressed}}",
profilesTab: "Probe profiles",
profilesHelp: "Prompt and expected marker for active quality probes. A missing marker is a hard failure.",
profileActive: "In use",
diff --git a/tools/egress-quality-guard/README.md b/tools/egress-quality-guard/README.md
index 2b37b06c..7c5d254b 100644
--- a/tools/egress-quality-guard/README.md
+++ b/tools/egress-quality-guard/README.md
@@ -43,6 +43,20 @@ your own traffic before allowing automatic quarantine.
records a generic connectivity probe for diagnosis, then uses the real
model-quality probe as the authority before re-enabling the node.
+Account-bound proxy templates such as Resin usernames containing `{account}`
+render a distinct sticky lease for each account. Scheduled node probes remain
+suppressed because one lease cannot represent its siblings. A passive anomaly
+removes only the audited account lease; after the hold, recovery pins a probe to
+that same account and node, renews an unhealthy hold, and clears the durable
+marker only with a matching CAS version. Routing stops enforcing a hold after
+its deadline, so a stopped sidecar cannot strand an account indefinitely.
+Rebinding an account atomically removes its old marker. If identity or the lease
+API is unavailable, the guard falls back to observation and never disables the
+shared node. Rendered proxy usernames and credentials never cross the API.
+Lease reconciliation uses opaque keyset pagination and scans the complete
+durable set. Recovery probes are capped per cycle and retry with exponential
+backoff, so a large expired queue cannot monopolize one guard cycle.
+
The public inference API cannot request a specific egress node or bypass a
disabled node. This capability is confined to the authenticated internal route.
Ambiguous probe-only 403 responses do not cool borrowed accounts; definitive
@@ -112,6 +126,10 @@ probe prompt, or model response body.
- Never deletes a node or changes account bindings.
- Never restores a node disabled by an operator.
+- Never applies whole-node quarantine to an account-bound `{account}` proxy. A
+ legacy quarantine still owned by the guard is released during reconciliation.
+- Lease recovery is pinned to the same account and node and uses an opaque CAS
+ version so stale probes cannot clear a newer quarantine.
- Refuses to quarantine below `qualityGuard.minimumHealthyNodes`.
- Strict mode overrides that floor rather than scheduling an unverified exit.
- Uses an exclusive process lock to prevent duplicate guards.
diff --git a/tools/egress-quality-guard/README.zh-CN.md b/tools/egress-quality-guard/README.zh-CN.md
index 6f4b07b1..2e8d2e23 100644
--- a/tools/egress-quality-guard/README.zh-CN.md
+++ b/tools/egress-quality-guard/README.zh-CN.md
@@ -23,6 +23,15 @@ Token/s,因此建议先观察 JSON 日志,再根据实际流量调整阈值
6. 隔离节点仍可接受管理员探测,但不会承载普通用户请求。
7. 冷却结束后记录一次通用连接探测用于诊断,再以真实模型质量探测作为恢复判据,账号绑定保持不变。
+Resin 用户名等代理模板包含 `{account}` 时,同一逻辑节点会按账号生成不同的粘性租约。
+这类节点不会执行无法代表全部租约的定时节点探测;被动审计出现异常时,后端只临时移出该
+审计关联的账号租约。冷却到期后,恢复探针固定使用同一账号与同一节点;异常会续期,健康时
+通过版本校验清理持久化标记。路由在隔离期限到期后不再强制摘流,避免 sidecar 停止时让孤儿
+状态永久卡住账号。账号换绑会原子清理旧标记;sidecar 或接口异常时只记录观测,绝不回退为
+整节点禁用。内部接口只传账号 ID、节点 ID 和随机版本号,不返回渲染后的 Resin 用户名或代理凭据。
+租约对账采用不透明游标完整分页;每轮恢复探针有固定上限,失败后按指数退避,避免大量到期租约
+长期占满单次守护循环。
+
普通 `/v1/*` 请求不能指定出口节点,也不能绕过节点禁用状态。
仅发生在质量探测中的模糊 403 不会冷却借用账号;明确的凭据失效、账号封禁和额度信号仍按原有规则处理。
@@ -70,6 +79,7 @@ Webhook,确认出口发生变化,再执行一次真实模型质量检测;
- 不删除节点,不修改账号绑定。
- 不会恢复管理员手动禁用的节点。
+- 不会对账号绑定的 `{account}` 代理执行整节点隔离;升级前仍由守护程序持有的旧隔离会在状态对账时解除。
- 启用节点数低于 `qualityGuard.minimumHealthyNodes` 时拒绝继续隔离。
- 严格模式会覆盖最低健康节点保护:无法确认质量时宁可无可用节点,也不调度可疑出口。
- 使用进程锁防止重复运行。
diff --git a/tools/egress-quality-guard/quality_guard.py b/tools/egress-quality-guard/quality_guard.py
index 584d10b6..0eb25be7 100755
--- a/tools/egress-quality-guard/quality_guard.py
+++ b/tools/egress-quality-guard/quality_guard.py
@@ -47,6 +47,11 @@ INTERNAL_API_PREFIX = "/api/internal/v1/quality-guard"
QUALITY_MARKER_PROFILE_ID = "quality-marker"
THROUGHPUT_PROFILE_ID = "throughput"
THINKING_GUARD_MIN_OUTPUT_TOKENS = 64
+LEASE_PAGE_SIZE = 1000
+LEASE_SCAN_MAX_PAGES = 1000
+LEASE_RECOVERY_MAX_PER_CYCLE = 8
+LEASE_RECOVERY_BACKOFF_BASE_SECONDS = 30
+LEASE_RECOVERY_BACKOFF_MAX_SECONDS = 1800
class GuardDisabled(RuntimeError):
@@ -321,8 +326,10 @@ class ApiClient:
result.add(node_id)
return result
- def quality_test(self, node_id: str, profile_id: str = "") -> dict[str, Any]:
+ def quality_test(self, node_id: str, profile_id: str = "", account_id: str = "") -> dict[str, Any]:
body = {"profileId": profile_id} if profile_id else {}
+ if account_id:
+ body["accountId"] = account_id
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/quality-test", body or None)
def connectivity_test(self, node_id: str) -> dict[str, Any]:
@@ -342,6 +349,42 @@ class ApiClient:
result = self._request("PATCH", f"{INTERNAL_API_PREFIX}/egress-nodes/batch", {"ids": [node_id], "enabled": enabled})
return int(result.get("updated") or 0)
+ def list_leases(self) -> list[dict[str, Any]]:
+ values: list[dict[str, Any]] = []
+ cursor = ""
+ seen_cursors: set[str] = set()
+ for _page in range(LEASE_SCAN_MAX_PAGES):
+ query = {"limit": LEASE_PAGE_SIZE}
+ if cursor:
+ query["cursor"] = cursor
+ payload = self._request("GET", f"{INTERNAL_API_PREFIX}/egress-leases?{urllib.parse.urlencode(query)}")
+ items = list(payload.get("items") or [])
+ values.extend(items)
+ if not payload.get("hasMore"):
+ return values
+ next_cursor = str(payload.get("nextCursor") or "")
+ if not next_cursor or next_cursor == cursor or next_cursor in seen_cursors:
+ raise RuntimeError("lease pagination did not advance")
+ seen_cursors.add(next_cursor)
+ cursor = next_cursor
+ raise RuntimeError("lease pagination exceeded the safety limit")
+
+ def quarantine_lease(self, node_id: str, account_id: str, reason: str) -> dict[str, Any]:
+ return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-leases/quarantine", {
+ "nodeId": node_id,
+ "accountId": account_id,
+ "reason": reason,
+ "quarantineSeconds": self.config.quarantine_seconds,
+ })
+
+ def restore_lease(self, node_id: str, account_id: str, version: str) -> bool:
+ result = self._request("POST", f"{INTERNAL_API_PREFIX}/egress-leases/restore", {
+ "nodeId": node_id,
+ "accountId": account_id,
+ "version": version,
+ })
+ return bool(result.get("restored"))
+
def rotate_node(self, node_id: str, old_exit_ip: str = "") -> dict[str, Any]:
if not self.config.rotation_url:
raise RuntimeError("rotation endpoint is not configured")
@@ -517,6 +560,9 @@ def generation_window_ms(first_token_ms: int, duration_ms: int, reasoning_tokens
def default_node_state() -> dict[str, Any]:
return {
+ "observe_only": False,
+ "observe_only_reason": "",
+ "quarantined_lease_count": 0,
"active_soft_strikes": 0,
"passive_soft_strikes": 0,
"error_strikes": 0,
@@ -630,6 +676,8 @@ class Guard:
self._resolved_node_ids = list(config.node_ids)
self.state.setdefault("started_at", time.time())
self.state.setdefault("recent_events", [])
+ self.state.setdefault("leases", {})
+ self.state.setdefault("lease_recovery", {})
ensure_statistics(self.state)
self._update_guard_metadata()
self._save()
@@ -678,6 +726,11 @@ class Guard:
current.setdefault(key, value)
return current
+ @staticmethod
+ def _is_lease_scoped(node: dict[str, Any]) -> bool:
+ """Return whether one logical node expands to account-specific sticky leases."""
+ return bool(node.get("accountBoundProxy"))
+
def _defer_no_account(self, state: dict[str, Any], node: dict[str, Any], now: float, event: str, **fields: Any) -> None:
state["last_probe_at"] = now
state["last_reason"] = "probe_no_account"
@@ -732,9 +785,213 @@ class Guard:
def _probe_account_unavailable(exc: Exception) -> bool:
return isinstance(exc, ApiError) and exc.code == "egressQualityProbeNoAccount"
+ @staticmethod
+ def _lease_key(node_id: str, account_id: str) -> str:
+ return f"{node_id}:{account_id}"
+
+ def _clear_lease_recovery(self, key: str) -> None:
+ self.state.setdefault("lease_recovery", {}).pop(key, None)
+
+ def _defer_lease_recovery(self, key: str, now: float) -> None:
+ recovery = self.state.setdefault("lease_recovery", {})
+ current = recovery.get(key) or {}
+ failures = min(16, int(current.get("failures") or 0) + 1)
+ delay = min(LEASE_RECOVERY_BACKOFF_MAX_SECONDS, LEASE_RECOVERY_BACKOFF_BASE_SECONDS * (2 ** (failures - 1)))
+ recovery[key] = {"failures": failures, "next_attempt_at": now + delay}
+
+ def _quarantine_lease(self, node: dict[str, Any], audit_value: dict[str, Any], reason: str, now: float) -> None:
+ node_id = str(node.get("id") or "")
+ account_id = str(audit_value.get("accountId") or "")
+ state = self._state_for(node_id)
+ request_id = str(audit_value.get("requestId") or "")
+ if not account_id:
+ state.update({"observe_only": True, "observe_only_reason": "missing_account_identity", "last_reason": reason})
+ self._bump_statistic("actions", "suppressed")
+ append_state_event(self.state, "lease_quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, request_id=request_id)
+ log_event("lease_quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, cause="missing_account_identity")
+ return
+ try:
+ lease = self.api.quarantine_lease(node_id, account_id, reason)
+ except Exception as exc:
+ state.update({"observe_only": True, "observe_only_reason": "lease_api_unavailable", "last_reason": reason})
+ self._bump_statistic("actions", "suppressed")
+ append_state_event(self.state, "lease_quarantine_failed", node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, request_id=request_id)
+ log_event("lease_quarantine_failed", node_id=node_id, node_name=node.get("name"), reason=reason, error_type=type(exc).__name__)
+ return
+ key = self._lease_key(node_id, account_id)
+ leases = self.state.setdefault("leases", {})
+ already_quarantined = key in leases
+ leases[key] = lease
+ self._clear_lease_recovery(key)
+ state.update({"observe_only": False, "observe_only_reason": "", "last_reason": reason})
+ event = "lease_quarantine_extended" if already_quarantined else "lease_quarantined"
+ if not already_quarantined:
+ state["quarantined_lease_count"] = int(state.get("quarantined_lease_count", 0)) + 1
+ self._bump_statistic("actions", "quarantined")
+ append_state_event(self.state, event, node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, request_id=request_id, cooldown_until=lease.get("cooldownUntil"))
+ self._save()
+ log_event(event, node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, cooldown_until=lease.get("cooldownUntil"))
+
+ def _extend_lease(self, node: dict[str, Any], lease: dict[str, Any], reason: str) -> bool:
+ node_id = str(lease.get("nodeId") or node.get("id") or "")
+ account_id = str(lease.get("accountId") or "")
+ try:
+ replacement = self.api.quarantine_lease(node_id, account_id, reason)
+ except Exception as exc:
+ log_event("lease_quarantine_extension_failed", node_id=node_id, node_name=node.get("name"), reason=reason, error_type=type(exc).__name__)
+ return False
+ key = self._lease_key(node_id, account_id)
+ self.state.setdefault("leases", {})[key] = replacement
+ self._clear_lease_recovery(key)
+ append_state_event(self.state, "lease_quarantine_extended", node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, cooldown_until=replacement.get("cooldownUntil"))
+ log_event("lease_quarantine_extended", node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id)
+ return True
+
+ def _recover_lease(self, node: dict[str, Any], lease: dict[str, Any], now: float) -> None:
+ node_id = str(lease.get("nodeId") or "")
+ account_id = str(lease.get("accountId") or "")
+ version = str(lease.get("version") or "")
+ if not node_id or not account_id or not version:
+ return
+ key = self._lease_key(node_id, account_id)
+ profile_id, profile = resolve_probe_profile(self.config.profiles_file, QUALITY_MARKER_PROFILE_ID)
+ self._bump_statistic("active", "total")
+ try:
+ result = self.api.quality_test(node_id, profile_id, account_id)
+ classification, reason = classify_result(result, self.config, profile)
+ except Exception as exc:
+ self._bump_statistic("active", "errors")
+ if not self._extend_lease(node, lease, "recovery_probe_error"):
+ self._defer_lease_recovery(key, now)
+ log_event("lease_recovery_probe_failed", node_id=node_id, node_name=node.get("name"), account_id=account_id, error_type=type(exc).__name__)
+ return
+ self._record_probe(node, result, classification, reason, now)
+ if classification != "healthy":
+ if not self._extend_lease(node, lease, reason):
+ self._defer_lease_recovery(key, now)
+ return
+ try:
+ restored = self.api.restore_lease(node_id, account_id, version)
+ except ApiError as exc:
+ if exc.code == "qualityLeaseConflict":
+ self._clear_lease_recovery(key)
+ log_event("lease_restore_stale", node_id=node_id, node_name=node.get("name"), account_id=account_id)
+ return
+ self._defer_lease_recovery(key, now)
+ log_event("lease_restore_failed", node_id=node_id, node_name=node.get("name"), account_id=account_id, error_type=type(exc).__name__)
+ return
+ except Exception as exc:
+ self._defer_lease_recovery(key, now)
+ log_event("lease_restore_failed", node_id=node_id, node_name=node.get("name"), account_id=account_id, error_type=type(exc).__name__)
+ return
+ if not restored:
+ self._defer_lease_recovery(key, now)
+ return
+ self.state.setdefault("leases", {}).pop(key, None)
+ self._clear_lease_recovery(key)
+ node_state = self._state_for(node_id)
+ node_state["quarantined_lease_count"] = max(0, int(node_state.get("quarantined_lease_count", 0)) - 1)
+ self._bump_statistic("actions", "restored")
+ append_state_event(self.state, "lease_restored", node_id=node_id, node_name=node.get("name"), reason="quality_probe_healthy", account_id=account_id)
+ log_event("lease_restored", node_id=node_id, node_name=node.get("name"), account_id=account_id, reason="quality_probe_healthy")
+
+ def _reconcile_leases(self, nodes: list[dict[str, Any]], now: float) -> bool:
+ node_by_id = {str(node.get("id") or ""): node for node in nodes}
+ try:
+ values = self.api.list_leases()
+ except Exception as exc:
+ log_event("lease_reconciliation_failed", error_type=type(exc).__name__)
+ return False
+ state_leases = self.state.setdefault("leases", {})
+ recovery_state = self.state.setdefault("lease_recovery", {})
+ backend_keys: set[str] = set()
+ due: list[tuple[dict[str, Any], dict[str, Any]]] = []
+ for node in nodes:
+ if self._is_lease_scoped(node):
+ self._state_for(str(node["id"]))["quarantined_lease_count"] = 0
+ for lease in values:
+ node_id = str(lease.get("nodeId") or "")
+ account_id = str(lease.get("accountId") or "")
+ if not node_id or not account_id:
+ continue
+ key = self._lease_key(node_id, account_id)
+ backend_keys.add(key)
+ state_leases[key] = lease
+ node = node_by_id.get(node_id)
+ if node is None or not self._is_lease_scoped(node):
+ continue
+ state = self._state_for(node_id)
+ state["observe_only"] = False
+ state["observe_only_reason"] = ""
+ state["quarantined_lease_count"] = int(state.get("quarantined_lease_count", 0)) + 1
+ if now >= float(lease.get("cooldownUntil") or 0):
+ retry = recovery_state.get(key) or {}
+ if now >= float(retry.get("next_attempt_at") or 0):
+ due.append((node, lease))
+ for key in list(state_leases):
+ if key not in backend_keys:
+ state_leases.pop(key, None)
+ recovery_state.pop(key, None)
+ for key in list(recovery_state):
+ if key not in backend_keys:
+ recovery_state.pop(key, None)
+ for node, lease in due[:LEASE_RECOVERY_MAX_PER_CYCLE]:
+ self._recover_lease(node, lease, now)
+ deferred = max(0, len(due) - LEASE_RECOVERY_MAX_PER_CYCLE)
+ if deferred:
+ log_event("lease_recovery_budget_exhausted", due=len(due), deferred=deferred, limit=LEASE_RECOVERY_MAX_PER_CYCLE)
+ return True
+
+ def _release_protected_leases(self, protected_node_ids: set[str], nodes: list[dict[str, Any]]) -> None:
+ if not protected_node_ids:
+ return
+ node_by_id = {str(node.get("id") or ""): node for node in nodes}
+ state_leases = self.state.setdefault("leases", {})
+ for key, lease in list(state_leases.items()):
+ node_id = str(lease.get("nodeId") or "")
+ if node_id not in protected_node_ids:
+ continue
+ account_id = str(lease.get("accountId") or "")
+ version = str(lease.get("version") or "")
+ try:
+ restored = self.api.restore_lease(node_id, account_id, version)
+ except Exception as exc:
+ log_event("protected_lease_release_failed", node_id=node_id, error_type=type(exc).__name__)
+ continue
+ if not restored:
+ continue
+ state_leases.pop(key, None)
+ node = node_by_id.get(node_id) or {}
+ state = self._state_for(node_id)
+ state["quarantined_lease_count"] = max(0, int(state.get("quarantined_lease_count", 0)) - 1)
+ self._bump_statistic("actions", "restored")
+ append_state_event(self.state, "lease_restored", node_id=node_id, node_name=node.get("name"), reason="fixed_fallback_node", account_id=account_id)
+ log_event("protected_lease_released", node_id=node_id, node_name=node.get("name"), account_id=account_id)
+
def _quarantine(self, nodes: list[dict[str, Any]], node: dict[str, Any], reason: str, now: float, recover_now: bool = True) -> None:
node_id = str(node["id"])
state = self._state_for(node_id)
+ if self._is_lease_scoped(node):
+ state.update({
+ "observe_only": True,
+ "observe_only_reason": "account_bound_proxy",
+ "last_reason": reason,
+ })
+ self._bump_statistic("actions", "suppressed")
+ append_state_event(
+ self.state,
+ "lease_scoped_quarantine_suppressed",
+ node_id=node_id,
+ node_name=node.get("name"),
+ reason=reason,
+ )
+ log_event(
+ "lease_scoped_quarantine_suppressed",
+ node_id=node_id,
+ node_name=node.get("name"),
+ reason=reason,
+ )
+ return
if not self._can_quarantine(nodes, node_id):
self._bump_statistic("actions", "suppressed")
log_event("quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, minimum_healthy=self.config.min_healthy_nodes)
@@ -993,13 +1250,80 @@ class Guard:
def _prepare_nodes(self, now: float) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str]]:
all_nodes = self.api.list_nodes()
+ lease_api_ready = self._reconcile_leases(all_nodes, now)
protected_node_ids = self.api.fixed_fallback_node_ids()
+ if lease_api_ready:
+ self._release_protected_leases(protected_node_ids, all_nodes)
previous_protected = set(str(value) for value in self.state.get("protected_node_ids", []))
if protected_node_ids != previous_protected:
self.state["protected_node_ids"] = sorted(protected_node_ids)
for node_id in sorted(protected_node_ids - previous_protected):
log_event("fixed_fallback_node_skipped", node_id=node_id)
state_nodes = self.state.setdefault("nodes", {})
+ release_failed_ids: set[str] = set()
+ # An account-bound proxy renders a different sticky lease for each
+ # account. Release any whole-node quarantine left by an older guard;
+ # current versions isolate the audited account lease instead.
+ for node in all_nodes:
+ node_id = str(node.get("id") or "")
+ if not node_id or not node.get("proxyConfigured"):
+ continue
+ existing = state_nodes.get(node_id)
+ if not self._is_lease_scoped(node):
+ if existing:
+ existing["observe_only"] = False
+ existing["observe_only_reason"] = ""
+ continue
+ state = self._state_for(node_id)
+ if not lease_api_ready:
+ state["observe_only"] = True
+ state["observe_only_reason"] = "lease_api_unavailable"
+ elif state.get("observe_only_reason") in {"account_bound_proxy", "lease_api_unavailable"}:
+ state["observe_only"] = False
+ state["observe_only_reason"] = ""
+ if not state.get("disabled_by_guard"):
+ continue
+ if not node.get("enabled"):
+ try:
+ updated = self.api.set_enabled(node_id, True)
+ except Exception as exc:
+ release_failed_ids.add(node_id)
+ log_event(
+ "lease_scoped_guard_release_failed",
+ node_id=node_id,
+ node_name=node.get("name"),
+ error_type=type(exc).__name__,
+ )
+ continue
+ if updated != 1:
+ release_failed_ids.add(node_id)
+ log_event(
+ "lease_scoped_guard_release_not_applied",
+ node_id=node_id,
+ node_name=node.get("name"),
+ updated=updated,
+ )
+ continue
+ node["enabled"] = True
+ self._bump_statistic("actions", "restored")
+ state.update({
+ "active_soft_strikes": 0,
+ "passive_soft_strikes": 0,
+ "error_strikes": 0,
+ "quarantined_until": 0.0,
+ "disabled_by_guard": False,
+ "last_reason": "",
+ "quarantine_source": "",
+ })
+ append_state_event(
+ self.state,
+ "lease_scoped_guard_released",
+ node_id=node_id,
+ node_name=node.get("name"),
+ reason="lease_scoped_node",
+ )
+ self._save()
+ log_event("lease_scoped_guard_released", node_id=node_id, node_name=node.get("name"))
# Making an enabled node a fixed fallback is an explicit operator
# override. Relinquish stale guard ownership before eligibility checks
# so strict mode cannot repeatedly attempt an invalid disable. A
@@ -1030,7 +1354,7 @@ class Guard:
tracked = bool((state_nodes.get(stale_id) or {}).get("disabled_by_guard"))
if stale_id not in present_ids or (stale_id not in managed_ids and not tracked):
del state_nodes[stale_id]
- skip_ids: set[str] = set()
+ skip_ids: set[str] = set(release_failed_ids)
if not nodes:
log_event("no_eligible_nodes")
return all_nodes, [], skip_ids
@@ -1067,6 +1391,8 @@ class Guard:
continue
if state.get("disabled_by_guard"):
skip_ids.add(node_id)
+ if self._is_lease_scoped(node):
+ continue
self._probe_quarantined(node, now)
return all_nodes, nodes, skip_ids
@@ -1076,6 +1402,9 @@ class Guard:
for node in nodes:
node_id = str(node["id"])
state = self._state_for(node_id)
+ if self._is_lease_scoped(node):
+ self._save()
+ continue
if node_id not in skip_ids and node.get("enabled") and not state.get("disabled_by_guard"):
self._probe_active(all_nodes, node, now)
self._save()
@@ -1175,15 +1504,18 @@ class Guard:
duration_ms=int(audit_value.get("durationMs") or 0),
strikes=int(state.get("passive_soft_strikes", 0)),
)
- log_event(
- "passive_immediate_quarantine",
- node_id=node_id,
- node_name=node.get("name"),
- classification=classification,
- reason=reason,
- output_tps=round(speed, 3),
- )
- self._quarantine(all_nodes, node, reason, now, recover_now=False)
+ if self._is_lease_scoped(node):
+ self._quarantine_lease(node, audit_value, reason, now)
+ else:
+ log_event(
+ "passive_immediate_quarantine",
+ node_id=node_id,
+ node_name=node.get("name"),
+ classification=classification,
+ reason=reason,
+ output_tps=round(speed, 3),
+ )
+ self._quarantine(all_nodes, node, reason, now, recover_now=False)
def run_passive_cycle(self) -> None:
now = time.time()
diff --git a/tools/egress-quality-guard/quality_guard_test.py b/tools/egress-quality-guard/quality_guard_test.py
index d6b574b7..e6ef7d9c 100644
--- a/tools/egress-quality-guard/quality_guard_test.py
+++ b/tools/egress-quality-guard/quality_guard_test.py
@@ -342,6 +342,28 @@ class ApiClientTests(unittest.TestCase):
}
self.assertEqual(client.fixed_fallback_node_ids(), {"9", "11"})
+ def test_list_leases_uses_stable_cursor_until_complete(self):
+ client = quality_guard.ApiClient(config())
+ requested_cursors = []
+
+ def request(_method, path, _body=None):
+ query = quality_guard.urllib.parse.parse_qs(quality_guard.urllib.parse.urlparse(path).query)
+ cursor = (query.get("cursor") or [""])[0]
+ requested_cursors.append(cursor)
+ if not cursor:
+ return {"items": [{"accountId": "1"}], "hasMore": True, "nextCursor": "next-page"}
+ return {"items": [{"accountId": "2"}], "hasMore": False, "nextCursor": ""}
+
+ client._request = request
+ self.assertEqual([value["accountId"] for value in client.list_leases()], ["1", "2"])
+ self.assertEqual(requested_cursors, ["", "next-page"])
+
+ def test_list_leases_rejects_non_advancing_cursor(self):
+ client = quality_guard.ApiClient(config())
+ client._request = lambda *_args, **_kwargs: {"items": [], "hasMore": True, "nextCursor": "same"}
+ with self.assertRaises(RuntimeError):
+ client.list_leases()
+
class FakeApi:
def __init__(self, nodes, results, audit_pages=None, fixed_fallback_ids=None):
@@ -352,7 +374,9 @@ class FakeApi:
self.enabled_calls = []
self.quality_calls = []
self.quality_profile_calls = []
+ self.quality_account_calls = []
self.rotation_calls = []
+ self.leases = {}
def list_nodes(self):
return self.nodes
@@ -360,9 +384,10 @@ class FakeApi:
def fixed_fallback_node_ids(self):
return set(self.fixed_fallback_ids)
- def quality_test(self, node_id, profile_id=""):
+ def quality_test(self, node_id, profile_id="", account_id=""):
self.quality_calls.append(node_id)
self.quality_profile_calls.append(profile_id)
+ self.quality_account_calls.append(account_id)
value = self.results.pop(0)
if isinstance(value, Exception):
raise value
@@ -388,6 +413,26 @@ class FakeApi:
return self.audit_pages.pop(0)
return {"items": [], "hasMore": False, "nextCursor": ""}
+ def list_leases(self):
+ return list(self.leases.values())
+
+ def quarantine_lease(self, node_id, account_id, reason):
+ key = f"{node_id}:{account_id}"
+ value = {
+ "nodeId": node_id, "accountId": account_id, "reason": reason,
+ "version": f"version-{len(self.leases) + 1:09d}", "cooldownUntil": time.time() + 300,
+ }
+ self.leases[key] = value
+ return value
+
+ def restore_lease(self, node_id, account_id, version):
+ key = f"{node_id}:{account_id}"
+ current = self.leases.get(key)
+ if current is None or current.get("version") != version:
+ raise quality_guard.ApiError(409, "qualityLeaseConflict", "stale")
+ del self.leases[key]
+ return True
+
class GuardTests(unittest.TestCase):
@staticmethod
@@ -444,6 +489,182 @@ class GuardTests(unittest.TestCase):
self.assertEqual(api.quality_calls, ["2"])
self.assertEqual(guard.state["protected_node_ids"], ["1"])
+ def test_fixed_fallback_releases_existing_account_lease_without_probe(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",))
+ nodes = self.nodes(2)
+ nodes[0]["accountBoundProxy"] = True
+ api = FakeApi(nodes, [], fixed_fallback_ids={"1"})
+ api.leases["1:101"] = {
+ "nodeId": "1", "accountId": "101", "reason": "hard_tps",
+ "version": "lease-version-0001", "cooldownUntil": time.time() + 300,
+ }
+ guard = quality_guard.Guard(cfg, api)
+ guard.run_active_cycle()
+ self.assertEqual(api.leases, {})
+ self.assertEqual(api.quality_calls, [])
+ self.assertEqual(guard.state["statistics"]["actions"]["restored"], 1)
+ self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_restored")
+
+ def test_account_bound_proxy_skips_scheduled_probe_and_stays_observable(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(
+ state_file=Path(directory) / "state.json",
+ lock_file=Path(directory) / "lock",
+ node_ids=("1",),
+ )
+ nodes = self.nodes(3)
+ nodes[0]["accountBoundProxy"] = True
+ api = FakeApi(nodes, [])
+ guard = quality_guard.Guard(cfg, api)
+ guard.run_active_cycle()
+
+ self.assertEqual(api.quality_calls, [])
+ self.assertEqual(api.enabled_calls, [])
+ self.assertTrue(nodes[0]["enabled"])
+ self.assertFalse(guard.state["nodes"]["1"]["observe_only"])
+ self.assertEqual(guard.state["nodes"]["1"]["observe_only_reason"], "")
+
+ def test_account_bound_proxy_records_passive_anomaly_without_node_quarantine(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(
+ state_file=Path(directory) / "state.json",
+ lock_file=Path(directory) / "lock",
+ mode="passive",
+ node_ids=("1",),
+ )
+ nodes = self.nodes(3)
+ nodes[0]["accountBoundProxy"] = True
+ api = FakeApi(nodes, [{"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}], [
+ {"items": [], "hasMore": False, "nextCursor": ""},
+ {"items": [self.audit("lease-hit", "1", 1200)], "hasMore": False, "nextCursor": ""},
+ ])
+ guard = quality_guard.Guard(cfg, api)
+ guard.run_passive_cycle()
+ guard.run_passive_cycle()
+
+ state = guard.state["nodes"]["1"]
+ self.assertEqual(api.enabled_calls, [])
+ self.assertTrue(nodes[0]["enabled"])
+ self.assertFalse(state["disabled_by_guard"])
+ self.assertEqual(state["last_classification"], "hard")
+ self.assertEqual(state["last_reason"], "hard_tps")
+ self.assertEqual(guard.state["statistics"]["actions"]["quarantined"], 1)
+ self.assertEqual(len(api.leases), 1)
+ self.assertEqual(
+ [event["event"] for event in guard.state["recent_events"]],
+ ["passive_audit_anomaly", "lease_quarantined"],
+ )
+ next(iter(api.leases.values()))["cooldownUntil"] = 0
+ guard.run_active_cycle()
+ self.assertEqual(api.quality_account_calls, ["101"])
+ self.assertEqual(api.leases, {})
+ self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_restored")
+
+ def test_repeated_account_anomaly_extends_one_lease_without_double_counting(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",))
+ nodes = self.nodes(2)
+ nodes[0]["accountBoundProxy"] = True
+ api = FakeApi(nodes, [])
+ guard = quality_guard.Guard(cfg, api)
+ audit = {"accountId": "101"}
+
+ guard._quarantine_lease(nodes[0], audit, "hard_tps", time.time())
+ guard._quarantine_lease(nodes[0], audit, "hard_tps", time.time())
+
+ self.assertEqual(len(api.leases), 1)
+ self.assertEqual(guard.state["nodes"]["1"]["quarantined_lease_count"], 1)
+ self.assertEqual(guard.state["statistics"]["actions"]["quarantined"], 1)
+ self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_quarantine_extended")
+
+ def test_due_lease_recovery_has_a_per_cycle_budget(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",))
+ nodes = self.nodes(2)
+ nodes[0]["accountBoundProxy"] = True
+ healthy = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
+ api = FakeApi(nodes, [healthy] * 20)
+ for index in range(20):
+ account_id = str(1000 + index)
+ api.leases[f"1:{account_id}"] = {
+ "nodeId": "1", "accountId": account_id, "reason": "hard_tps",
+ "version": f"lease-version-{index:04d}", "cooldownUntil": 0,
+ }
+ guard = quality_guard.Guard(cfg, api)
+ guard.run_active_cycle()
+ self.assertEqual(len(api.quality_account_calls), quality_guard.LEASE_RECOVERY_MAX_PER_CYCLE)
+ self.assertEqual(len(api.leases), 20 - quality_guard.LEASE_RECOVERY_MAX_PER_CYCLE)
+ guard.run_active_cycle()
+ self.assertEqual(len(api.quality_account_calls), quality_guard.LEASE_RECOVERY_MAX_PER_CYCLE * 2)
+
+ def test_failed_lease_recovery_is_backed_off(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",))
+ nodes = self.nodes(2)
+ nodes[0]["accountBoundProxy"] = True
+ api = FakeApi(nodes, [RuntimeError("probe failed"), RuntimeError("must not run immediately")])
+ api.leases["1:101"] = {
+ "nodeId": "1", "accountId": "101", "reason": "hard_tps",
+ "version": "lease-version-0001", "cooldownUntil": 0,
+ }
+ api.quarantine_lease = mock.Mock(side_effect=RuntimeError("backend unavailable"))
+ guard = quality_guard.Guard(cfg, api)
+ guard.run_active_cycle()
+ guard.run_active_cycle()
+ self.assertEqual(api.quality_account_calls, ["101"])
+ retry = guard.state["lease_recovery"]["1:101"]
+ self.assertGreater(retry["next_attempt_at"], time.time())
+
+ def test_account_bound_proxy_releases_only_guard_owned_legacy_quarantine(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(
+ state_file=Path(directory) / "state.json",
+ lock_file=Path(directory) / "lock",
+ node_ids=("1",),
+ )
+ nodes = self.nodes(3)
+ nodes[0].update({"accountBoundProxy": True, "enabled": False})
+ api = FakeApi(nodes, [])
+ guard = quality_guard.Guard(cfg, api)
+ state = guard._state_for("1")
+ state.update({"disabled_by_guard": True, "last_reason": "hard_tps", "quarantined_until": time.time() + 300})
+ guard.run_active_cycle()
+
+ self.assertEqual(api.enabled_calls, [("1", True)])
+ self.assertTrue(nodes[0]["enabled"])
+ self.assertFalse(state["disabled_by_guard"])
+ self.assertFalse(state["observe_only"])
+ self.assertEqual(guard.state["statistics"]["actions"]["restored"], 1)
+ self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_scoped_guard_released")
+
+ nodes[0]["enabled"] = False
+ guard.run_active_cycle()
+ self.assertEqual(api.enabled_calls, [("1", True)])
+ self.assertFalse(nodes[0]["enabled"])
+
+ def test_account_bound_proxy_keeps_ownership_when_legacy_release_fails(self):
+ with tempfile.TemporaryDirectory() as directory:
+ cfg = config(
+ state_file=Path(directory) / "state.json",
+ lock_file=Path(directory) / "lock",
+ node_ids=("1",),
+ )
+ nodes = self.nodes(3)
+ nodes[0].update({"accountBoundProxy": True, "enabled": False})
+ api = FakeApi(nodes, [])
+ api.set_enabled = mock.Mock(side_effect=RuntimeError("temporary backend failure"))
+ guard = quality_guard.Guard(cfg, api)
+ state = guard._state_for("1")
+ state.update({"disabled_by_guard": True, "last_reason": "hard_tps", "quarantined_until": 0})
+ guard.run_active_cycle()
+
+ api.set_enabled.assert_called_once_with("1", True)
+ self.assertEqual(api.quality_calls, [])
+ self.assertFalse(nodes[0]["enabled"])
+ self.assertTrue(state["disabled_by_guard"])
+ self.assertFalse(state["observe_only"])
+
def test_enabled_node_promoted_to_fixed_fallback_releases_guard_ownership(self):
with tempfile.TemporaryDirectory() as directory:
cfg = config(
@@ -990,7 +1211,7 @@ class GuardTests(unittest.TestCase):
"provider": "grok_build", "streaming": True,
"statusCode": 200, "firstTokenMs": 200, "durationMs": 200 + generation_ms,
"outputTokens": output_tokens, "reasoningTokens": min(100, max(0, output_tokens - 1)),
- "egressNodeId": node_id, "errorCode": None,
+ "accountId": "101", "egressNodeId": node_id, "errorCode": None,
}
From c9c10a3fbd91180a4329c8c23b2d68d299fec030 Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 01:07:01 +0800
Subject: [PATCH 02/13] fix: treat only streamed thinking as quality-hold
evidence
Usage.reasoning_tokens, empty reasoning items, and the Chat SSE stub
are not proof of thinking. Degraded upstreams fill those fields and
then dump visible tokens, so the hold used to fail-open as 200.
Require reasoning/summary deltas or encrypted_content before delivering.
An empty stub waits until terminal so ciphertext that arrives at the end
is not withheld.
---
.../application/gateway/quality_retry.go | 35 +++++--
.../application/gateway/quality_retry_scan.go | 85 +++++++++-------
.../application/gateway/quality_retry_test.go | 97 ++++++++++++++++++-
3 files changed, 168 insertions(+), 49 deletions(-)
diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go
index 78cd164e..5af478d9 100644
--- a/backend/internal/application/gateway/quality_retry.go
+++ b/backend/internal/application/gateway/quality_retry.go
@@ -50,12 +50,16 @@ type QualityRetryRuntime struct {
// QualityStreamSignals is the hold classifier input. Tests drive this
// directly and via ObserveQualityChunk on SSE fixtures.
type QualityStreamSignals struct {
- HasThinking bool
- VisibleTokens int64
- ReasoningTokens int64
- OutputTokens int64
- Terminal bool
- HoldExpired bool
+ HasThinking 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.
+ ReasoningStarted bool
+ VisibleTokens int64
+ ReasoningTokens int64
+ OutputTokens int64
+ Terminal bool
+ HoldExpired bool
}
// QualityVerdict is the hold decision for one upstream stream.
@@ -110,16 +114,23 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime {
}
// ClassifyQualityHold decides whether a held stream may be forwarded.
-// Thinking (or reasoning tokens) always delivers. A finished or expired
-// sample with enough visible output and no reasoning is 降智 and withheld.
+// 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.
// 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. Wait for usage/terminal so
+// encrypted thinking (tokens arrive at the end) is not withheld, and so
+// 200 + 推理·高 + reasoning=0 is not delivered the moment the stub appears.
func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict {
if minOutput <= 0 {
minOutput = defaultQualityMinOutput
}
- if sig.HasThinking || sig.ReasoningTokens > 0 {
+ if sig.HasThinking {
return QualityDeliver
}
output := sig.OutputTokens
@@ -127,6 +138,9 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
output = sig.VisibleTokens
}
enough := output >= minOutput
+ if sig.ReasoningStarted && !sig.Terminal && !sig.HoldExpired {
+ return QualityWait
+ }
if sig.Terminal {
if output <= 0 {
return QualityWait
@@ -143,6 +157,9 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
if output <= 0 {
return QualityWait
}
+ if enough {
+ return QualityWithhold
+ }
return QualityDeliver
}
return QualityWait
diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go
index 3a29d8b9..b0ffffb4 100644
--- a/backend/internal/application/gateway/quality_retry_scan.go
+++ b/backend/internal/application/gateway/quality_retry_scan.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"io"
+ "strings"
"sync"
"time"
"unicode/utf8"
@@ -21,15 +22,16 @@ const (
)
type qualityScanState struct {
- protocol string
- pending []byte
- hasThinking bool
- visibleRunes int
- reasoningTokens int64
- outputTokens int64
- usage Usage
- responseID string
- terminal bool
+ protocol string
+ pending []byte
+ hasThinking bool
+ reasoningStarted bool
+ visibleRunes int
+ reasoningTokens int64
+ outputTokens int64
+ usage Usage
+ responseID string
+ terminal bool
}
type qualityReadResult struct {
@@ -135,12 +137,16 @@ func (s *qualityScanState) signals() QualityStreamSignals {
if s.usage.Reported && s.usage.OutputTokens > output {
output = s.usage.OutputTokens
}
+ // 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).
return QualityStreamSignals{
- HasThinking: s.hasThinking || s.reasoningTokens > 0 || s.usage.ReasoningTokens > 0,
- VisibleTokens: visible,
- ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens),
- OutputTokens: output,
- Terminal: s.terminal,
+ HasThinking: s.hasThinking,
+ ReasoningStarted: s.reasoningStarted || s.hasThinking,
+ VisibleTokens: visible,
+ ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens),
+ OutputTokens: output,
+ Terminal: s.terminal,
}
}
@@ -165,7 +171,8 @@ func ObserveQualityChunk(state *qualityScanState, chunk []byte) {
continue
}
if bytes.Equal(line, []byte(qualityReasoningSSEComment)) {
- state.hasThinking = true
+ // Timing stub only. 降智 still emits this, then usage.reasoning_tokens=0.
+ state.reasoningStarted = true
continue
}
if !bytes.HasPrefix(line, []byte("data:")) {
@@ -228,9 +235,6 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
state.usage.ResponseModel = event.Model
state.outputTokens = event.Usage.CompletionTokens
state.reasoningTokens = event.Usage.CompletionTokensDetails.ReasoningTokens
- if state.reasoningTokens > 0 {
- state.hasThinking = true
- }
}
for _, choice := range event.Choices {
delta := choice.Delta
@@ -246,17 +250,33 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
}
}
+type qualityReasoningItem struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ EncryptedContent string `json:"encrypted_content"`
+}
+
+func noteResponsesReasoningItem(state *qualityScanState, item qualityReasoningItem) {
+ if !strings.EqualFold(strings.TrimSpace(item.Type), "reasoning") {
+ return
+ }
+ if strings.TrimSpace(item.ID) != "" {
+ state.reasoningStarted = true
+ }
+ if strings.TrimSpace(item.EncryptedContent) != "" {
+ state.hasThinking = true
+ }
+}
+
func observeQualityResponses(state *qualityScanState, payload []byte) {
var event struct {
Type string `json:"type"`
Delta string `json:"delta"`
- Item struct {
- ID string `json:"id"`
- Type string `json:"type"`
- } `json:"item"`
+ Item qualityReasoningItem
Response *struct {
- ID string `json:"id"`
- Model string `json:"model"`
+ ID string `json:"id"`
+ Model string `json:"model"`
+ Output []qualityReasoningItem `json:"output"`
Usage *struct {
OutputTokens int64 `json:"output_tokens"`
InputTokens int64 `json:"input_tokens"`
@@ -277,10 +297,8 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
if event.Delta != "" {
state.hasThinking = true
}
- case "response.output_item.added":
- if event.Item.Type == "reasoning" && event.Item.ID != "" {
- state.hasThinking = true
- }
+ case "response.output_item.added", "response.output_item.done":
+ noteResponsesReasoningItem(state, event.Item)
case "response.output_text.delta":
if event.Delta != "" {
noteVisibleContent(state, event.Delta)
@@ -290,6 +308,9 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
if state.responseID == "" {
state.responseID = event.Response.ID
}
+ for _, item := range event.Response.Output {
+ noteResponsesReasoningItem(state, item)
+ }
if event.Response.Usage != nil {
state.usage.Reported = true
state.usage.InputTokens = event.Response.Usage.InputTokens
@@ -299,9 +320,6 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
state.usage.ResponseModel = event.Response.Model
state.outputTokens = event.Response.Usage.OutputTokens
state.reasoningTokens = event.Response.Usage.OutputTokensDetails.ReasoningTokens
- if state.reasoningTokens > 0 {
- state.hasThinking = true
- }
}
}
}
@@ -332,7 +350,7 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
state.terminal = true
case "content_block_start":
if event.ContentBlock.Type == "thinking" {
- state.hasThinking = true
+ state.reasoningStarted = true
}
case "content_block_delta":
if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
@@ -348,9 +366,6 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
state.usage.ReasoningTokens = event.Usage.OutputTokensDetails.ThinkingTokens
state.outputTokens = event.Usage.OutputTokens
state.reasoningTokens = event.Usage.OutputTokensDetails.ThinkingTokens
- if state.reasoningTokens > 0 {
- state.hasThinking = true
- }
}
}
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index 3c0035d8..fd7cde61 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -32,12 +32,14 @@ func TestClassifyQualityHold(t *testing.T) {
want QualityVerdict
}{
{name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 10}, want: QualityDeliver},
- {name: "reasoning tokens deliver", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, 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},
{name: "short no think delivers", sig: QualityStreamSignals{VisibleTokens: 10, Terminal: true}, want: QualityDeliver},
{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 terminal enough withhold", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, Terminal: true}, want: QualityWithhold},
{name: "wait for more", sig: QualityStreamSignals{VisibleTokens: 8}, want: QualityWait},
{name: "hold expired short delivers", sig: QualityStreamSignals{VisibleTokens: 8, HoldExpired: true}, want: QualityDeliver},
{name: "hold expired empty waits", sig: QualityStreamSignals{HoldExpired: true}, want: QualityWait},
@@ -265,14 +267,99 @@ func TestObserveQualityChunkShortNoThink(t *testing.T) {
func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) {
t.Parallel()
- state := qualityScanState{protocol: qualityProtocolResponses}
- ObserveQualityChunk(&state, []byte(sse(
+ fake := qualityScanState{protocol: qualityProtocolResponses}
+ ObserveQualityChunk(&fake, []byte(sse(
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
+ `data: {"type":"response.output_text.delta","delta":"hello hello hello hello hello hello hello hello"}`,
+ `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
+ )))
+ fakeSig := fake.signals()
+ if fakeSig.HasThinking {
+ t.Fatalf("usage-only reasoning tokens must not count as thinking: %#v", fakeSig)
+ }
+ if !fakeSig.ReasoningStarted || fakeSig.ReasoningTokens != 60 {
+ t.Fatalf("usage-only signals = %#v", fakeSig)
+ }
+ if ClassifyQualityHold(fakeSig, 32) != QualityWithhold {
+ t.Fatalf("usage-only reasoning with no deltas must withhold: %#v", fakeSig)
+ }
+
+ real := qualityScanState{protocol: qualityProtocolResponses}
+ ObserveQualityChunk(&real, []byte(sse(
+ `data: {"type":"response.reasoning_summary_text.delta","delta":"plan the fix"}`,
`data: {"type":"response.output_text.delta","delta":"hello"}`,
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
)))
- if ClassifyQualityHold(state.signals(), 32) != QualityDeliver {
- t.Fatalf("responses reasoning item should deliver: %#v", state.signals())
+ realSig := real.signals()
+ if !realSig.HasThinking || realSig.ReasoningTokens != 60 {
+ t.Fatalf("streamed summary must count as thinking: %#v", realSig)
+ }
+ if ClassifyQualityHold(realSig, 32) != QualityDeliver {
+ t.Fatalf("streamed reasoning summary should deliver: %#v", realSig)
+ }
+
+ 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.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
+ )))
+ encSig := encrypted.signals()
+ if !encSig.HasThinking || encSig.ReasoningTokens != 60 {
+ t.Fatalf("encrypted reasoning item must count as thinking: %#v", encSig)
+ }
+ if ClassifyQualityHold(encSig, 32) != QualityDeliver {
+ t.Fatalf("encrypted thinking should deliver: %#v", encSig)
+ }
+}
+
+func TestObserveQualityChunkEmptyReasoningStubIsNotThinking(t *testing.T) {
+ t.Parallel()
+ content := strings.Repeat("word ", 40)
+ chat := qualityScanState{protocol: qualityProtocolChat}
+ ObserveQualityChunk(&chat, []byte(sse(
+ ": grok2api-reasoning-start",
+ `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`,
+ `data: {"usage":{"completion_tokens":45,"completion_tokens_details":{"reasoning_tokens":0}}}`,
+ "data: [DONE]",
+ )))
+ chatSig := chat.signals()
+ if chatSig.HasThinking {
+ t.Fatalf("chat SSE stub must not count as thinking: %#v", chatSig)
+ }
+ if !chatSig.ReasoningStarted || !chatSig.Terminal || chatSig.ReasoningTokens != 0 {
+ t.Fatalf("chat stub signals = %#v", chatSig)
+ }
+ if ClassifyQualityHold(chatSig, 32) != QualityWithhold {
+ t.Fatalf("chat stub + 0 reasoning must withhold, got %s (%#v)", ClassifyQualityHold(chatSig, 32), chatSig)
+ }
+
+ mid := qualityScanState{protocol: qualityProtocolChat}
+ ObserveQualityChunk(&mid, []byte(sse(
+ ": grok2api-reasoning-start",
+ `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`,
+ )))
+ midSig := mid.signals()
+ if midSig.HasThinking || !midSig.ReasoningStarted || midSig.Terminal {
+ t.Fatalf("midstream stub signals = %#v", midSig)
+ }
+ if ClassifyQualityHold(midSig, 32) != QualityWait {
+ t.Fatalf("midstream stub must wait for usage, got %s (%#v)", ClassifyQualityHold(midSig, 32), midSig)
+ }
+
+ responses := qualityScanState{protocol: qualityProtocolResponses}
+ ObserveQualityChunk(&responses, []byte(sse(
+ `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
+ `data: {"type":"response.output_text.delta","delta":"`+content+`"}`,
+ `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":45,"output_tokens_details":{"reasoning_tokens":0}}}}`,
+ )))
+ respSig := responses.signals()
+ if respSig.HasThinking {
+ t.Fatalf("empty responses reasoning item must not count as thinking: %#v", respSig)
+ }
+ if ClassifyQualityHold(respSig, 32) != QualityWithhold {
+ t.Fatalf("empty reasoning item + 0 tokens must withhold, got %s (%#v)", ClassifyQualityHold(respSig, 32), respSig)
}
}
From 731e95b9242ad4d2b521ff3955d95b2b0f478a91 Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 01:08:34 +0800
Subject: [PATCH 03/13] fix: hold TUI tool-schema turns, skip only in-flight
tool results
Grok TUI declares a tools array on every agent request, including the
first thinking turn. Skipping hold on that schema forwarded
missing-thinking streams as HTTP 200.
Keep the replay-safety skip for in-flight tool output
(function_call_output, tool_result, role=tool). Compact skip and
previous_response_id pinning are unchanged.
---
.../application/gateway/quality_retry.go | 45 ++++++++++++++++---
.../application/gateway/quality_retry_test.go | 36 +++++++++++++--
2 files changed, 72 insertions(+), 9 deletions(-)
diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go
index 78cd164e..bccf06c2 100644
--- a/backend/internal/application/gateway/quality_retry.go
+++ b/backend/internal/application/gateway/quality_retry.go
@@ -270,10 +270,11 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole {
return false
}
- // Retrying a tool-capable request can repeat external side effects. Tool
- // requests remain outside this feature until they have their own replay
- // safety contract.
- if qualityRequestUsesTools(input.Body) {
+ // Retrying an in-flight tool *result* can repeat external side effects.
+ // Grok TUI always declares a tools schema even on the first thinking
+ // turn; skipping that schema would disable the hold for every agent
+ // request. Only skip when the body already contains tool output.
+ if qualityRequestHasInFlightToolResults(input.Body) {
return false
}
// Aliases are rewritten before this gate, so inspect the effective request
@@ -289,11 +290,43 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
}
func qualityRequestUsesTools(body []byte) bool {
- var payload map[string]json.RawMessage
+ return qualityRequestHasInFlightToolResults(body)
+}
+
+func qualityRequestHasInFlightToolResults(body []byte) bool {
+ var payload any
if json.Unmarshal(body, &payload) != nil {
return false
}
- return nonEmptyJSONCollection(payload["tools"]) || nonEmptyJSONCollection(payload["functions"])
+ return jsonTreeHasInFlightToolResult(payload)
+}
+
+func jsonTreeHasInFlightToolResult(node any) bool {
+ switch typed := node.(type) {
+ case map[string]any:
+ role := jsonNodeString(typed["role"])
+ typ := jsonNodeString(typed["type"])
+ if role == "tool" || typ == "function_call_output" || typ == "tool_result" || typ == "tool_use_output" {
+ return true
+ }
+ for _, child := range typed {
+ if jsonTreeHasInFlightToolResult(child) {
+ return true
+ }
+ }
+ case []any:
+ for _, child := range typed {
+ if jsonTreeHasInFlightToolResult(child) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func jsonNodeString(value any) string {
+ text, _ := value.(string)
+ return strings.ToLower(strings.TrimSpace(text))
}
func qualityRequestDisablesReasoning(body []byte) bool {
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index 3c0035d8..1df6e136 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -560,14 +560,44 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
{name: "responses reasoning none", body: `{"reasoning":{"effort":"none"}}`},
{name: "messages thinking disabled", body: `{"thinking":{"type":"disabled"}}`},
{name: "messages zero thinking budget", body: `{"thinking":{"type":"enabled","budget_tokens":0}}`},
- {name: "client tools", body: `{"tools":[{"type":"function","function":{"name":"charge"}}]}`},
- {name: "legacy functions", body: `{"functions":[{"name":"charge"}]}`},
} {
t.Run(test.name, func(t *testing.T) {
request := input
request.Body = []byte(test.body)
if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
- t.Fatal("explicitly disabled reasoning and tool requests must not be held")
+ t.Fatal("explicitly disabled reasoning must not be held")
+ }
+ })
+ }
+ for _, test := range []struct {
+ name string
+ body string
+ }{
+ {name: "client tools schema", body: `{"tools":[{"type":"function","function":{"name":"charge"}}]}`},
+ {name: "legacy functions schema", body: `{"functions":[{"name":"charge"}]}`},
+ {name: "tui tools schema plus user input", body: `{"model":"grok-4.6","tools":[{"type":"function","name":"read_file"}],"input":[{"role":"user","content":"hello"}]}`},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ request := input
+ request.Body = []byte(test.body)
+ if !shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
+ t.Fatal("tools schema alone must still hold so TUI thinking turns are classified")
+ }
+ })
+ }
+ for _, test := range []struct {
+ name string
+ body string
+ }{
+ {name: "function_call_output", body: `{"input":[{"type":"function_call_output","call_id":"call_1","output":"done"}]}`},
+ {name: "tool_result", body: `{"input":[{"type":"tool_result","tool_use_id":"tool_1","content":"done"}]}`},
+ {name: "role tool", body: `{"messages":[{"role":"tool","content":"done"}]}`},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ request := input
+ request.Body = []byte(test.body)
+ if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
+ t.Fatal("in-flight tool results must not be held")
}
})
}
From 68e58814336646c2aececb3b05f1489c8b1fedd9 Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 01:07:29 +0800
Subject: [PATCH 04/13] fix: fill required output_text.annotations for Grok CLI
serde
Grok CLI treats annotations as a required field. A missing key fails
deserialization with "missing field annotations" and the TUI retries
the turn. Keep existing citation arrays untouched.
---
.../transport/http/inference/handler_test.go | 20 +++++++++++++
.../http/inference/responses_compat.go | 29 +++++++++++++++++++
2 files changed, 49 insertions(+)
diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go
index 9215bd34..29f1fe57 100644
--- a/backend/internal/transport/http/inference/handler_test.go
+++ b/backend/internal/transport/http/inference/handler_test.go
@@ -1166,6 +1166,26 @@ func TestSanitizeResponsesDoesNotAddResponseIDToErrorEvent(t *testing.T) {
}
}
+func TestSanitizeResponsesFillsMissingOutputTextAnnotations(t *testing.T) {
+ state := &responsesCompatState{}
+ added := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","item":{"type":"message","content":[{"type":"output_text","text":"hi"}]}}`+"\n"), state)
+ if !bytes.Contains(added, []byte(`"annotations":[]`)) {
+ t.Fatalf("item output_text missing annotations: %s", added)
+ }
+ completed := rewriteResponsesDataLine([]byte(`data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"hi"}]}]}}`+"\n"), state)
+ if !bytes.Contains(completed, []byte(`"annotations":[]`)) {
+ t.Fatalf("completed output_text missing annotations: %s", completed)
+ }
+ part := rewriteResponsesDataLine([]byte(`data: {"type":"response.content_part.added","part":{"type":"output_text","text":"hi"}}`+"\n"), state)
+ if !bytes.Contains(part, []byte(`"annotations":[]`)) {
+ t.Fatalf("content_part output_text missing annotations: %s", part)
+ }
+ kept := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.done","item":{"type":"message","content":[{"type":"output_text","text":"hi","annotations":[{"type":"url_citation","url":"https://x.test"}]}]}}`+"\n"), state)
+ if !bytes.Contains(kept, []byte(`"url":"https://x.test"`)) || bytes.Contains(kept, []byte(`"annotations":[]`)) {
+ t.Fatalf("existing annotations were replaced: %s", kept)
+ }
+}
+
func TestResponsesCompatBoundsUnterminatedLineBuffer(t *testing.T) {
state := &responsesCompatState{}
chunk := bytes.Repeat([]byte{'x'}, maxStreamEventInspectionBytes+1)
diff --git a/backend/internal/transport/http/inference/responses_compat.go b/backend/internal/transport/http/inference/responses_compat.go
index 4926d54b..731d1968 100644
--- a/backend/internal/transport/http/inference/responses_compat.go
+++ b/backend/internal/transport/http/inference/responses_compat.go
@@ -221,6 +221,35 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b
}
}
}
+ if ensureOutputTextAnnotations(event) {
+ changed = true
+ }
+ return changed
+}
+
+// Grok CLI serde requires output_text.annotations even when there are no
+// citations. Missing the field makes a retry fail with
+// "serialization error: missing field `annotations`".
+func ensureOutputTextAnnotations(node any) bool {
+ changed := false
+ switch typed := node.(type) {
+ case map[string]any:
+ if stringAny(typed["type"]) == "output_text" && typed["annotations"] == nil {
+ typed["annotations"] = []any{}
+ changed = true
+ }
+ for _, key := range []string{"item", "part", "response", "content", "output", "delta"} {
+ if ensureOutputTextAnnotations(typed[key]) {
+ changed = true
+ }
+ }
+ case []any:
+ for _, child := range typed {
+ if ensureOutputTextAnnotations(child) {
+ changed = true
+ }
+ }
+ }
return changed
}
From dc87764154d6b7439d604c74207a5d09bad45950 Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 01:09:37 +0800
Subject: [PATCH 05/13] fix: retry empty completed streams instead of waiting
for idle
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
response.completed / [DONE] with zero tokens used to keep the quality
hold in Wait until the idle timeout. The client already had HTTP 200
headers and saw a 50–120s Retrying spinner.
Finish the peek immediately and surface errQualityEmptyStream so the
attempt loop rotates. Open empty hangs still wait for idle and do not
fail-open as HTTP 200.
---
.../application/gateway/quality_retry_scan.go | 6 +++
.../application/gateway/quality_retry_test.go | 42 +++++++++++++++++++
2 files changed, 48 insertions(+)
diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go
index 3a29d8b9..0d57a530 100644
--- a/backend/internal/application/gateway/quality_retry_scan.go
+++ b/backend/internal/application/gateway/quality_retry_scan.go
@@ -376,6 +376,12 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string,
if verdict := ClassifyQualityHold(sig, cfg.MinOutputTokens); verdict != QualityWait {
return newPrefixReplay(&held, pump), verdict, state.usage, state.responseID, nil
}
+ // A completed empty stream must rotate immediately. Waiting for idle
+ // timeout after response.completed / [DONE] surfaces HTTP 200 with 0
+ // tokens and makes Grok TUI retry for 50–120s.
+ if sig.Terminal {
+ return finishQualityPeek(&held, pump, &state, cfg)
+ }
select {
case <-ctx.Done():
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index 3c0035d8..a37aad1a 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -461,6 +461,48 @@ func TestPeekQualityStreamHoldTimeoutEmptyDoesNotFailOpen(t *testing.T) {
}
}
+func TestPeekQualityStreamEmptyCompletedRetriesWithoutIdle(t *testing.T) {
+ t.Parallel()
+ started := time.Now()
+ replay, verdict, _, _, err := peekQualityStream(
+ context.Background(),
+ io.NopCloser(strings.NewReader(sse(
+ `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":0}}}`,
+ ))),
+ qualityProtocolResponses,
+ QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: 2 * time.Second},
+ )
+ if replay != nil {
+ defer replay.Close()
+ }
+ if !errors.Is(err, errQualityEmptyStream) {
+ t.Fatalf("peek error = %v, want empty stream", err)
+ }
+ if verdict != QualityWait {
+ t.Fatalf("verdict = %s, want wait so the attempt loop retries as transport", verdict)
+ }
+ if time.Since(started) > 500*time.Millisecond {
+ t.Fatalf("empty completed stream waited %s, want immediate retry", time.Since(started))
+ }
+
+ started = time.Now()
+ replay, verdict, _, _, err = peekQualityStream(
+ context.Background(),
+ io.NopCloser(strings.NewReader(sse("data: [DONE]"))),
+ qualityProtocolChat,
+ QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: 2 * time.Second},
+ )
+ if replay != nil {
+ defer replay.Close()
+ }
+ if !errors.Is(err, errQualityEmptyStream) {
+ t.Fatalf("chat empty [DONE] peek error = %v, want empty stream", err)
+ }
+ if time.Since(started) > 500*time.Millisecond {
+ t.Fatalf("empty chat [DONE] waited %s, want immediate retry", time.Since(started))
+ }
+}
+
func TestPeekQualityStreamEmptyEOFRequestsAnotherAccount(t *testing.T) {
t.Parallel()
replay, verdict, _, _, err := peekQualityStream(
From 78c17a83b3a42a750c522b96228189718ed32b86 Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 02:38:32 +0800
Subject: [PATCH 06/13] fix: allow clearing account cooldown and configure
empty-stream penalty
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Empty SSE idle timeouts currently write a hardcoded 24h cooldown via
qualityIdleAccountCooldown. Toggling enabled does not reset health, so a
single-account pool stays on 429 upstream_cooling until the operator
edits sqlite and restarts.
Add POST /api/admin/v1/accounts/:id/clear-cooldown (API + UI) which
zeros failure_count/cooldown_until/last_error. UpdateHealth already
publishes InvalidationAccountHealthChanged, so runtimeStore=memory
selector overlays are replaced.
Expose qualityGuard.requestRetry.idleAccountCooldown (1m–168h, default
24h) independently of missing-thinking accountCooldown. PATCH enabled
while cooling returns enabledDoesNotClearCooldown so the UI can warn.
Closes #976
---
backend/internal/app/application.go | 13 ++--
.../internal/application/account/service.go | 21 +++++++
.../application/gateway/quality_retry.go | 6 ++
.../application/gateway/quality_retry_test.go | 2 +-
.../internal/application/gateway/service.go | 13 ++--
.../application/gateway/service_test.go | 10 ++-
backend/internal/infra/config/config.go | 8 ++-
backend/internal/infra/config/config_test.go | 8 ++-
.../transport/http/account/handler.go | 20 ++++++
.../transport/http/account/handler_test.go | 61 +++++++++++++++++++
config.example.yaml | 4 ++
.../src/features/accounts/accounts-api.ts | 6 ++
.../src/features/accounts/accounts-page.tsx | 18 +++++-
frontend/src/shared/i18n/index.ts | 6 ++
14 files changed, 178 insertions(+), 18 deletions(-)
diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go
index 7f648c53..169a11a8 100644
--- a/backend/internal/app/application.go
+++ b/backend/internal/app/application.go
@@ -491,12 +491,13 @@ 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(),
+ 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(),
}
}
diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go
index bfb1843f..7a4bb35f 100644
--- a/backend/internal/application/account/service.go
+++ b/backend/internal/application/account/service.go
@@ -2279,6 +2279,27 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie
return s.Get(ctx, updated.ID)
}
+// ClearCooldown resets request-path health so a cooled account can be
+// scheduled again. UpdateHealth publishes InvalidationAccountHealthChanged,
+// which overwrites the selector memory overlay (runtimeStore=memory).
+func (s *Service) ClearCooldown(ctx context.Context, id uint64) (View, error) {
+ value, err := s.accounts.Get(ctx, id)
+ if err != nil {
+ return View{}, mapRepositoryError(err)
+ }
+ if err := s.accounts.UpdateHealth(ctx, value.ID, value.Provider, 0, nil, "", false); err != nil {
+ return View{}, mapRepositoryError(err)
+ }
+ updated, err := s.accounts.Get(ctx, id)
+ if err != nil {
+ return View{}, mapRepositoryError(err)
+ }
+ return View{
+ Credential: updated,
+ Quota: QuotaView{Type: QuotaTypeUnknown, Source: "unknown", Status: QuotaStatusActive},
+ }, nil
+}
+
// MarkBuildAPIFallback 幂等写入 Build 账号 XAI 推理回退标记;失败不吞掉,调用方可重试。
func (s *Service) MarkBuildAPIFallback(ctx context.Context, id uint64, enabled bool) error {
return mapRepositoryError(s.accounts.MarkBuildAPIFallback(ctx, id, enabled))
diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go
index 78cd164e..c6134fcc 100644
--- a/backend/internal/application/gateway/quality_retry.go
+++ b/backend/internal/application/gateway/quality_retry.go
@@ -45,6 +45,9 @@ type QualityRetryRuntime struct {
MinOutputTokens int64
OnExhausted string
AccountCooldown time.Duration
+ // IdleAccountCooldown is applied to truly empty upstream streams
+ // (idle timeout / empty peek). Missing-thinking still uses AccountCooldown.
+ IdleAccountCooldown time.Duration
}
// QualityStreamSignals is the hold classifier input. Tests drive this
@@ -90,6 +93,9 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime {
if cfg.AccountCooldown <= 0 {
cfg.AccountCooldown = defaultMissingThinkingCooldown
}
+ if cfg.IdleAccountCooldown <= 0 {
+ cfg.IdleAccountCooldown = qualityIdleAccountCooldown
+ }
cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted)
return cfg
}
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index 3c0035d8..7543ed09 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -894,7 +894,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 != 32 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 3*time.Second || got.AccountCooldown != 24*time.Hour {
+ if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 32 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 3*time.Second || got.AccountCooldown != 24*time.Hour || got.IdleAccountCooldown != 24*time.Hour {
t.Fatalf("defaults = %#v", got)
}
}
diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go
index b4b0136f..c5d764b1 100644
--- a/backend/internal/application/gateway/service.go
+++ b/backend/internal/application/gateway/service.go
@@ -1059,7 +1059,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
lease.completeSelectorObservation(successful)
budget := newFinalizationBudget(string(operation), string(route.Provider))
if isUpstreamStreamFailure(errorCode) {
- status, retryAfter := streamFailureHealthPenalty(errorCode, usage)
+ status, retryAfter := streamFailureHealthPenalty(errorCode, usage, s.qualityRetryConfig().IdleAccountCooldown)
if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error {
return s.selector.MarkFailureAfterSuccess(stageCtx, credential, status, retryAfter)
}); err != nil {
@@ -1536,10 +1536,10 @@ attemptLoop:
logPrefix = "quality_peek_empty"
}
writeCtx, writeCancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout)
- if markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, http.StatusGatewayTimeout, qualityIdleAccountCooldown); markErr != nil {
+ if markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, http.StatusGatewayTimeout, holdCfg.IdleAccountCooldown); markErr != nil {
s.logger.Warn(logPrefix+"_cooldown_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", markErr)
} else {
- s.logger.Warn(logPrefix+"_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", qualityIdleAccountCooldown)
+ s.logger.Warn(logPrefix+"_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", holdCfg.IdleAccountCooldown)
}
writeCancel()
}
@@ -1684,9 +1684,12 @@ func isUpstreamStreamFailure(errorCode string) bool {
}
}
-func streamFailureHealthPenalty(errorCode string, usage Usage) (int, time.Duration) {
+func streamFailureHealthPenalty(errorCode string, usage Usage, idleCooldown time.Duration) (int, time.Duration) {
if errorCode == "upstream_stream_idle_timeout" && !usage.OutputObserved && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 {
- return http.StatusGatewayTimeout, qualityIdleAccountCooldown
+ if idleCooldown <= 0 {
+ idleCooldown = qualityIdleAccountCooldown
+ }
+ return http.StatusGatewayTimeout, idleCooldown
}
return 0, 0
}
diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go
index 0f35a833..e5a90a9b 100644
--- a/backend/internal/application/gateway/service_test.go
+++ b/backend/internal/application/gateway/service_test.go
@@ -4350,16 +4350,20 @@ func TestIsUpstreamStreamFailureIncludesIdleTimeout(t *testing.T) {
func TestStreamFailureHealthPenaltyOnlyLongCoolsTrulyEmptyIdle(t *testing.T) {
t.Parallel()
- status, cooldown := streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{})
- if status != http.StatusGatewayTimeout || cooldown != qualityIdleAccountCooldown {
+ status, cooldown := streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{}, 15*time.Minute)
+ if status != http.StatusGatewayTimeout || cooldown != 15*time.Minute {
t.Fatalf("empty idle penalty = (%d, %s)", status, cooldown)
}
+ status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{}, 0)
+ if status != http.StatusGatewayTimeout || cooldown != qualityIdleAccountCooldown {
+ t.Fatalf("zero idle cooldown must fall back to default (%d, %s)", status, cooldown)
+ }
for _, usage := range []Usage{
{OutputObserved: true},
{OutputTokens: 1},
{ReasoningTokens: 1},
} {
- status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", usage)
+ status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", usage, 15*time.Minute)
if status != 0 || cooldown != 0 {
t.Fatalf("non-empty idle usage %#v received long penalty (%d, %s)", usage, status, cooldown)
}
diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go
index da19074f..fbd49c7b 100644
--- a/backend/internal/infra/config/config.go
+++ b/backend/internal/infra/config/config.go
@@ -294,6 +294,9 @@ type QualityGuardRequestRetryConfig struct {
MinOutputTokens int `yaml:"minOutputTokens"`
OnExhausted string `yaml:"onExhausted"`
AccountCooldown Duration `yaml:"accountCooldown"`
+ // IdleAccountCooldown cools an account after a truly empty upstream
+ // stream. Independent of accountCooldown (missing-thinking). Zero uses 24h.
+ IdleAccountCooldown Duration `yaml:"idleAccountCooldown"`
}
type ClientKeyDefaultsConfig struct {
@@ -799,6 +802,9 @@ func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) erro
if d := value.AccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) {
return errors.New("qualityGuard.requestRetry.accountCooldown 必须在 1m 到 168h 之间")
}
+ if d := value.IdleAccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) {
+ return errors.New("qualityGuard.requestRetry.idleAccountCooldown 必须在 1m 到 168h 之间")
+ }
return nil
}
@@ -932,7 +938,7 @@ func defaultConfig() Config {
MinimumGenerationWindow: Duration(time.Second), RotationTimeout: Duration(45 * time.Second),
RequestRetry: QualityGuardRequestRetryConfig{
MaxAttempts: 6, HoldTimeout: Duration(3 * time.Second), MinOutputTokens: 32, OnExhausted: "fail_closed",
- AccountCooldown: Duration(24 * time.Hour),
+ AccountCooldown: Duration(24 * time.Hour), IdleAccountCooldown: Duration(24 * time.Hour),
},
},
ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent},
diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go
index c7441e5c..6244a68e 100644
--- a/backend/internal/infra/config/config_test.go
+++ b/backend/internal/infra/config/config_test.go
@@ -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() != 3*time.Second || got.MinOutputTokens != 32 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 24*time.Hour {
+ if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 3*time.Second || got.MinOutputTokens != 32 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 24*time.Hour || got.IdleAccountCooldown.Value() != 24*time.Hour {
t.Fatalf("requestRetry defaults = %#v", got)
}
}
@@ -248,6 +248,12 @@ func TestQualityGuardRequestRetryAccountCooldownBounds(t *testing.T) {
if (err != nil) != test.wantErr {
t.Fatalf("validate cooldown %s: err=%v, wantErr=%t", test.value, err, test.wantErr)
}
+ err = validateQualityGuardRequestRetry(QualityGuardRequestRetryConfig{
+ Enabled: true, IdleAccountCooldown: Duration(test.value),
+ })
+ if (err != nil) != test.wantErr {
+ t.Fatalf("validate idle cooldown %s: err=%v, wantErr=%t", test.value, err, test.wantErr)
+ }
})
}
}
diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go
index 729ea2b0..c3ec991a 100644
--- a/backend/internal/transport/http/account/handler.go
+++ b/backend/internal/transport/http/account/handler.go
@@ -165,6 +165,7 @@ func (h *Handler) Register(router *gin.RouterGroup) {
router.DELETE("/accounts", h.batchDelete)
router.PATCH("/accounts/:id", h.update)
router.DELETE("/accounts/:id", h.delete)
+ router.POST("/accounts/:id/clear-cooldown", h.clearCooldown)
router.POST("/accounts/:id/refresh-token", h.refreshToken)
router.POST("/accounts/:id/refresh-billing", h.refreshBilling)
router.POST("/accounts/:id/refresh-quota", h.refreshWebQuota)
@@ -307,6 +308,9 @@ type accountResponse struct {
FailureCount int `json:"failureCount"`
CooldownUntil *time.Time `json:"cooldownUntil,omitempty"`
LastError string `json:"lastError,omitempty"`
+ // EnabledDoesNotClearCooldown is set on PATCH when enabled was changed
+ // while the account is still cooling. Toggling enabled is not a health reset.
+ EnabledDoesNotClearCooldown bool `json:"enabledDoesNotClearCooldown,omitempty"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
LinkedAccountID uint64 `json:"linkedAccountId,omitempty,string"`
LinkedName string `json:"linkedAccountName,omitempty"`
@@ -1255,6 +1259,9 @@ func (h *Handler) update(c *gin.Context) {
return
}
result := newAccountResponse(value)
+ if request.Enabled != nil && result.CooldownUntil != nil && time.Now().UTC().Before(*result.CooldownUntil) {
+ result.EnabledDoesNotClearCooldown = true
+ }
if request.BuildSuperEntitled != nil {
if synchronizer, ok := h.sync.(accountModelSynchronizer); ok {
result.ModelSyncFailed = synchronizer.SyncModels(c.Request.Context(), id) != nil
@@ -1263,6 +1270,19 @@ func (h *Handler) update(c *gin.Context) {
response.Success(c, http.StatusOK, result)
}
+func (h *Handler) clearCooldown(c *gin.Context) {
+ id, ok := pathID(c)
+ if !ok {
+ return
+ }
+ value, err := h.service.ClearCooldown(c.Request.Context(), id)
+ if err != nil {
+ h.writeServiceError(c, "accountClearCooldownFailed", err, http.StatusInternalServerError, "清除账号冷却失败")
+ return
+ }
+ response.Success(c, http.StatusOK, newAccountResponse(value))
+}
+
func (h *Handler) delete(c *gin.Context) {
id, ok := pathID(c)
if !ok {
diff --git a/backend/internal/transport/http/account/handler_test.go b/backend/internal/transport/http/account/handler_test.go
index fdb1c23e..5030f767 100644
--- a/backend/internal/transport/http/account/handler_test.go
+++ b/backend/internal/transport/http/account/handler_test.go
@@ -11,6 +11,7 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
+ "strconv"
"strings"
"sync/atomic"
"testing"
@@ -224,6 +225,66 @@ func TestLinkedDeleteMissingAccountReturnsNotFound(t *testing.T) {
}
}
+func TestClearCooldownResetsHealthAndSelectorCache(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ ctx := context.Background()
+ database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "clear-cooldown.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer database.Close()
+ if err := database.InitializeSchema(ctx); err != nil {
+ t.Fatal(err)
+ }
+ repo := relational.NewAccountRepository(database)
+ until := time.Now().UTC().Add(24 * time.Hour)
+ created, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{
+ Provider: accountdomain.ProviderBuild, Name: "cooled", SourceKey: "cooled",
+ EncryptedAccessToken: "token", Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
+ Priority: 100, MaxConcurrent: 1,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.UpdateHealth(ctx, created.ID, created.Provider, 3, &until, "upstream status 504", false); err != nil {
+ t.Fatal(err)
+ }
+ service := accountapp.NewService(repo, nil, nil, nil, nil, nil, nil)
+ handler := NewHandler(service, nil)
+
+ recorder := httptest.NewRecorder()
+ ginContext, _ := gin.CreateTestContext(recorder)
+ ginContext.Params = []gin.Param{{Key: "id", Value: strconv.FormatUint(created.ID, 10)}}
+ ginContext.Request = httptest.NewRequest("POST", "/api/admin/v1/accounts/"+strconv.FormatUint(created.ID, 10)+"/clear-cooldown", nil)
+ handler.clearCooldown(ginContext)
+ if recorder.Code != 200 {
+ t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
+ }
+ if strings.Contains(recorder.Body.String(), `"cooldownUntil"`) || strings.Contains(recorder.Body.String(), `"failureCount":3`) {
+ t.Fatalf("cooldown still present: %s", recorder.Body.String())
+ }
+ if !strings.Contains(recorder.Body.String(), `"failureCount":0`) {
+ t.Fatalf("failureCount not reset: %s", recorder.Body.String())
+ }
+
+ stored, err := repo.Get(ctx, created.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if stored.FailureCount != 0 || stored.CooldownUntil != nil || stored.LastError != "" {
+ t.Fatalf("persisted health = failure=%d cooldown=%v last=%q", stored.FailureCount, stored.CooldownUntil, stored.LastError)
+ }
+
+ missing := httptest.NewRecorder()
+ missingCtx, _ := gin.CreateTestContext(missing)
+ missingCtx.Params = []gin.Param{{Key: "id", Value: "999999"}}
+ missingCtx.Request = httptest.NewRequest("POST", "/api/admin/v1/accounts/999999/clear-cooldown", nil)
+ handler.clearCooldown(missingCtx)
+ if missing.Code != 404 {
+ t.Fatalf("missing status = %d, body = %s", missing.Code, missing.Body.String())
+ }
+}
+
func (s *accountSynchronizerStub) Sync(_ context.Context, accountIDs ...uint64) accountsyncapp.Result {
s.accountIDs = append(s.accountIDs, accountIDs...)
return accountsyncapp.Result{Succeeded: len(accountIDs)}
diff --git a/config.example.yaml b/config.example.yaml
index be69a127..52cc1765 100644
--- a/config.example.yaml
+++ b/config.example.yaml
@@ -159,3 +159,7 @@ qualityGuard:
# First missing-thinking hit cools the account; a later hit after the
# cooldown expires disables it.
accountCooldown: 24h
+ # Empty SSE / idle-timeout penalty. Independent of accountCooldown.
+ # Single-account pools should set this lower; toggling enabled does not
+ # clear cooldown — use POST /api/admin/v1/accounts/:id/clear-cooldown.
+ idleAccountCooldown: 24h
diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts
index 5e25d3a6..9de174ce 100644
--- a/frontend/src/features/accounts/accounts-api.ts
+++ b/frontend/src/features/accounts/accounts-api.ts
@@ -102,6 +102,7 @@ export type AccountDTO = {
failureCount: number;
cooldownUntil?: string;
lastError?: string;
+ enabledDoesNotClearCooldown?: boolean;
lastUsedAt?: string;
linkedAccountId?: string;
linkedAccountName?: string;
@@ -193,6 +194,7 @@ const accountValidator = hasShape({
egressNodeId: isOptional(isString), egressAssignmentMode: isOptional(isOneOf("manual", "auto")),
lastRefreshErrorStatus: isOptional(isNumber), lastRefreshErrorCode: isOptional(isString), lastRefreshErrorMessage: isOptional(isString), lastRefreshErrorResponse: isOptional(isString), priority: isNumber, maxConcurrent: isNumber, minimumRemaining: isNumber,
failureCount: isNumber, cooldownUntil: isOptional(isString), lastError: isOptional(isString), lastUsedAt: isOptional(isString),
+ enabledDoesNotClearCooldown: isOptional(isBoolean),
linkedAccountId: isOptional(isString), linkedAccountName: isOptional(isString), linkedProvider: isOptional(isOneOf("grok_build", "grok_web")), linkedAccounts: isOptional(isArrayOf(linkedAccountValidator)),
createdAt: isString, billing: isOptional(billingValidator), quota: quotaValidator, quotaWindows: isOptional(isArrayOf(quotaWindowValidator)),
});
@@ -309,6 +311,10 @@ export function refreshAccountToken(id: string): Promise {
return apiRequest(`/api/admin/v1/accounts/${id}/refresh-token`, { method: "POST" }, decodeAccount);
}
+export function clearAccountCooldown(id: string): Promise {
+ return apiRequest(`/api/admin/v1/accounts/${id}/clear-cooldown`, { method: "POST" }, decodeAccount);
+}
+
export function acceptWebAccountTerms(id: string): Promise<{ completed: boolean }> {
return apiRequest(`/api/admin/v1/accounts/web/${id}/accept-terms`, { method: "POST" }, decodeBooleanResult<{ completed: boolean }>("completed"));
}
diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx
index e0c4185f..4e40f8a3 100644
--- a/frontend/src/features/accounts/accounts-page.tsx
+++ b/frontend/src/features/accounts/accounts-page.tsx
@@ -1,6 +1,6 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { ArrowRight, ClipboardPaste, Compass, Download, ExternalLink, FileUp, Link, MoreHorizontal, Pencil, Plus, RefreshCw, RotateCw, Search, SquareTerminal, Trash2, TriangleAlert, Webhook } from "lucide-react";
+import { ArrowRight, ClipboardPaste, Compass, Download, ExternalLink, FileUp, Link, MoreHorizontal, Pencil, Plus, RefreshCw, RotateCw, Search, SquareTerminal, TimerOff, Trash2, TriangleAlert, Webhook } from "lucide-react";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
@@ -37,6 +37,7 @@ import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/tabl
import {
acceptWebAccountTerms,
cleanupAccounts,
+ clearAccountCooldown,
deleteAccount,
deleteAccounts,
previewAccountDeletion,
@@ -344,6 +345,7 @@ export function AccountsPage() {
if (entitlementChanged) void queryClient.invalidateQueries({ queryKey: ["models"] });
setEditing(null);
if (account.modelSyncFailed) toast.warning(t("accounts.updatedWithModelSyncFailure"));
+ else if (account.enabledDoesNotClearCooldown) toast.warning(t("accounts.enabledDoesNotClearCooldown"));
else toast.success(t("accounts.updated"));
},
onError: showError,
@@ -507,6 +509,15 @@ export function AccountsPage() {
onError: showError,
});
+ const clearCooldownMutation = useMutation({
+ mutationFn: clearAccountCooldown,
+ onSuccess: () => {
+ invalidateAccountData();
+ toast.success(t("accounts.cooldownCleared"));
+ },
+ onError: showError,
+ });
+
const quotaMutation = useMutation({
mutationFn: refreshAccountQuota,
onSuccess: () => {
@@ -1512,6 +1523,11 @@ export function AccountsPage() {
/>
) : null}
{provider === "grok_build" ? tokenMutation.mutate(account.id)}>{t("accounts.refreshToken")} : null}
+ {account.cooldownUntil && new Date(account.cooldownUntil) > new Date() ? (
+ clearCooldownMutation.mutate(account.id)} disabled={clearCooldownMutation.isPending}>
+ {t("accounts.clearCooldown")}
+
+ ) : null}
provider === "grok_build" ? billingMutation.mutate(account.id) : quotaMutation.mutate(account.id)}>{provider === "grok_build" ? t("accounts.refreshBilling") : t("accounts.refreshModeQuota")}
{ resetLinkedDeleteState(); setDeleting(account); }}>{t("common.delete")}
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts
index 8dea5ba8..c19b174d 100644
--- a/frontend/src/shared/i18n/index.ts
+++ b/frontend/src/shared/i18n/index.ts
@@ -2198,6 +2198,9 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor
});
Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, {
+ clearCooldown: "解除冷却",
+ cooldownCleared: "账号冷却已清除,可重新调度",
+ enabledDoesNotClearCooldown: "已开关账号,但冷却状态未变。请用「解除冷却」清除 cooldownUntil。",
importAuth: "导入账号或 RT 文件", quickImportRT: "快速导入 RT",
quickImportRTTitle: "快速导入 Grok Build Refresh Token", quickImportRTDescription: "支持粘贴多个 xAI Refresh Token,或上传每行一个 RT 的 TXT 文件。导入时会先换取 access token,后续自动续期会沿用对应的 OAuth client ID。",
refreshTokens: "Refresh Token(每行一个)", refreshTokenPlaceholder: "refresh_token_1\nrt=refresh_token_2\nrefresh_token=refresh_token_3",
@@ -2210,6 +2213,9 @@ Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, {
+ clearCooldown: "Clear cooldown",
+ cooldownCleared: "Account cooldown cleared; the account can be scheduled again",
+ enabledDoesNotClearCooldown: "Enabled state changed, but cooldown is unchanged. Use Clear cooldown to reset cooldownUntil.",
importAuth: "Import accounts or RTs", quickImportRT: "Quick import RTs",
quickImportRTTitle: "Quick import Grok Build refresh tokens", quickImportRTDescription: "Paste xAI refresh tokens or upload a TXT file with one RT per line. Import exchanges each RT for an access token, and later renewals retain its OAuth client ID.",
refreshTokens: "Refresh tokens (one per line)", refreshTokenPlaceholder: "refresh_token_1\nrt=refresh_token_2\nrefresh_token=refresh_token_3",
From 9bb6b48549e3615db92ef44037335a1d4cafabfa Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 11:43:23 +0800
Subject: [PATCH 07/13] fix: hold TUI after-tool turns instead of skipping
in-flight results
Grok TUI tools run locally. The next /v1/responses body already contains
function_call_output; retrying it on another account only regenerates the
model turn and does not re-execute tools. Skipping hold on that body let
0-thinking dumps through on the common agent loop.
---
.../application/gateway/quality_retry.go | 16 +++++-----------
.../application/gateway/quality_retry_test.go | 7 +++++--
2 files changed, 10 insertions(+), 13 deletions(-)
diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go
index bccf06c2..c1ac2760 100644
--- a/backend/internal/application/gateway/quality_retry.go
+++ b/backend/internal/application/gateway/quality_retry.go
@@ -270,13 +270,11 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole {
return false
}
- // Retrying an in-flight tool *result* can repeat external side effects.
- // Grok TUI always declares a tools schema even on the first thinking
- // turn; skipping that schema would disable the hold for every agent
- // request. Only skip when the body already contains tool output.
- if qualityRequestHasInFlightToolResults(input.Body) {
- return false
- }
+ // Grok TUI always declares a tools schema, and after local tools run the
+ // next /v1/responses body already contains function_call_output. Retrying
+ // that body on another account does not re-execute TUI tools — it only
+ // regenerates the model turn. Skipping hold here let 0-thinking dumps
+ // through on the common agent loop. Keep holding.
// 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.
@@ -289,10 +287,6 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
return modeldomain.SupportsReasoningForProvider(route.Provider, route.UpstreamModel)
}
-func qualityRequestUsesTools(body []byte) bool {
- return qualityRequestHasInFlightToolResults(body)
-}
-
func qualityRequestHasInFlightToolResults(body []byte) bool {
var payload any
if json.Unmarshal(body, &payload) != nil {
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index 1df6e136..f2c2a52f 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -596,8 +596,11 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
request := input
request.Body = []byte(test.body)
- if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
- t.Fatal("in-flight tool results must not be held")
+ if !qualityRequestHasInFlightToolResults(request.Body) {
+ t.Fatal("fixture must still be detected as tool output")
+ }
+ if !shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
+ t.Fatal("in-flight tool results must still be held so 0-thinking agent turns are classified")
}
})
}
From 24ce972b37941e5e084a18d13ebe1cdb321166ee Mon Sep 17 00:00:00 2001
From: lij768423-svg
Date: Thu, 20 Aug 2026 11:43:23 +0800
Subject: [PATCH 08/13] fix: emit response.failed with required model for Grok
TUI serde
TUI 0.2.93 treats any response.incomplete as fatal max_tokens_truncation,
ignoring incomplete_details.reason, so stream aborts killed the turn.
serde also requires model on response.failed / completed; a missing key
fails deserialization. Always emit response.failed and fill model from
stream metadata or the last seen response event.
---
.../transport/http/inference/handler.go | 35 ++++++++++++-------
.../transport/http/inference/handler_test.go | 26 ++++++++++----
.../http/inference/responses_compat.go | 11 ++++++
3 files changed, 53 insertions(+), 19 deletions(-)
diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go
index af803a0f..a8b09ba3 100644
--- a/backend/internal/transport/http/inference/handler.go
+++ b/backend/internal/transport/http/inference/handler.go
@@ -1418,21 +1418,30 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad
}
compat.rememberFromMeta(meta)
id := compat.ensureID()
- response := map[string]any{
- "id": id,
- "object": "response",
- "created_at": compat.createdAt,
- "completed_at": compat.createdAt,
- "status": "incomplete",
- "output": []any{},
- "error": nil,
- "incomplete_details": map[string]any{"reason": code},
+ // Grok TUI 0.2.93 treats any response.incomplete as fatal
+ // max_tokens_truncation (not retryable), ignoring incomplete_details.reason.
+ // Stream aborts are transport failures — emit response.failed so the
+ // client can retry instead of killing the turn.
+ model := strings.TrimSpace(meta.Model)
+ if model == "" {
+ model = strings.TrimSpace(compat.model)
}
- if model := strings.TrimSpace(meta.Model); model != "" {
- response["model"] = model
+ response := map[string]any{
+ "id": id,
+ "object": "response",
+ "created_at": compat.createdAt,
+ "completed_at": compat.createdAt,
+ "status": "failed",
+ "model": model,
+ "output": []any{},
+ "error": map[string]any{
+ "code": code,
+ "message": message,
+ "type": "server_error",
+ },
}
event := map[string]any{
- "type": "response.incomplete",
+ "type": "response.failed",
"id": id,
"sequence_number": meta.SequenceNumber + 1,
"response": response,
@@ -1442,7 +1451,7 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad
if err != nil {
return nil
}
- return []byte("event: response.incomplete\ndata: " + string(payload) + "\n\n")
+ return []byte("event: response.failed\ndata: " + string(payload) + "\n\n")
case streamProtocolAnthropic:
payload, err := json.Marshal(map[string]any{
"type": "error",
diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go
index 9215bd34..0d526d64 100644
--- a/backend/internal/transport/http/inference/handler_test.go
+++ b/backend/internal/transport/http/inference/handler_test.go
@@ -991,7 +991,7 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) {
want []string
}{
{name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_stream_idle_timeout"`, "data: [DONE]"}},
- {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.incomplete"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"incomplete_details"`}},
+ {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.failed"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"code":"upstream_stream_idle_timeout"`, `"status":"failed"`, `"model":`}},
{name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, "上游流式响应长时间无数据"}},
}
for _, test := range tests {
@@ -1046,7 +1046,7 @@ func TestCopyStreamFlushesUnterminatedResponsesTailBeforeAbort(t *testing.T) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
- if !strings.Contains(got, `"delta":"partial"`) || !strings.Contains(got, "\n\nevent: response.incomplete") {
+ if !strings.Contains(got, `"delta":"partial"`) || !strings.Contains(got, "\n\nevent: response.failed") {
t.Fatalf("unterminated tail and abort event were not separated: %q", got)
}
if marked != 1 {
@@ -1070,7 +1070,7 @@ func TestCopyStreamDropsMalformedResponsesTailBeforeAbort(t *testing.T) {
if strings.Contains(got, string(malformed)) {
t.Fatalf("malformed tail leaked before terminal event: %q", got)
}
- if !strings.Contains(got, `"type":"response.incomplete"`) {
+ if !strings.Contains(got, `"type":"response.failed"`) {
t.Fatalf("abort event missing after malformed tail: %q", got)
}
}
@@ -1099,7 +1099,7 @@ func TestCopyStreamWritesTerminalOnIncompleteEOF(t *testing.T) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
- if !strings.Contains(got, `"type":"response.incomplete"`) || !strings.Contains(got, `"reason":"upstream_stream_incomplete"`) {
+ if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"code":"upstream_stream_incomplete"`) {
t.Fatalf("incomplete EOF missing terminal SSE event: %q", got)
}
}
@@ -1111,8 +1111,22 @@ func TestSanitizeResponsesFillsMissingIDs(t *testing.T) {
t.Fatalf("item id not filled: %s", got)
}
got = rewriteResponsesDataLine([]byte(`data: {"type":"response.created","response":{"status":"in_progress"}}`+"\n"), state)
- if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) {
- t.Fatalf("response id/created_at not filled: %s", got)
+ if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) || !bytes.Contains(got, []byte(`"model":`)) {
+ t.Fatalf("response id/created_at/model not filled: %s", got)
+ }
+}
+
+func TestCopyStreamAbortTrailerAlwaysIncludesModel(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ _, err := copyStream(context.Writer, &idleErrorReader{}, streamProtocolResponses, nil)
+ if !errors.Is(err, errUpstreamStreamRead) {
+ t.Fatalf("copy error = %v", err)
+ }
+ got := recorder.Body.String()
+ if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"model":`) {
+ t.Fatalf("abort trailer missing model: %q", got)
}
}
diff --git a/backend/internal/transport/http/inference/responses_compat.go b/backend/internal/transport/http/inference/responses_compat.go
index 4926d54b..ba7e619d 100644
--- a/backend/internal/transport/http/inference/responses_compat.go
+++ b/backend/internal/transport/http/inference/responses_compat.go
@@ -12,6 +12,7 @@ import (
type responsesCompatState struct {
responseID string
createdAt int64
+ model string
itemSeq int
itemIDs map[int64]string
usedItemIDs map[string]struct{}
@@ -102,6 +103,9 @@ func (s *responsesCompatState) rememberFromMeta(meta responseMetadata) {
if id := strings.TrimSpace(meta.ResponseID); id != "" {
s.responseID = id
}
+ if model := strings.TrimSpace(meta.Model); model != "" {
+ s.model = model
+ }
s.ensureID()
}
@@ -173,6 +177,13 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b
resp["output"] = []any{}
changed = true
}
+ if model := strings.TrimSpace(stringAny(resp["model"])); model != "" {
+ state.model = model
+ } else {
+ // Grok TUI serde requires `model` on response.failed / completed.
+ resp["model"] = state.model
+ changed = true
+ }
if errObj, ok := resp["error"].(map[string]any); ok && strings.TrimSpace(stringAny(errObj["id"])) == "" {
errObj["id"] = "err_" + strings.TrimPrefix(state.ensureID(), "resp_")
changed = true
From 5f156cd3f54d88f39935830fd63b90b6b9745e53 Mon Sep 17 00:00:00 2001
From: Chenyme <118253778+chenyme@users.noreply.github.com>
Date: Thu, 20 Aug 2026 14:56:31 +0800
Subject: [PATCH 09/13] fix: preserve real thinking evidence across protocol
conversion
---
.../application/gateway/quality_retry.go | 10 +-
.../application/gateway/quality_retry_scan.go | 45 ++++++---
.../application/gateway/quality_retry_test.go | 94 ++++++++++++++++++-
.../conversation/conversation_test.go | 44 +++++++++
.../infra/provider/conversation/stream.go | 30 ++++++
.../transport/http/inference/handler.go | 43 +++++++--
.../transport/http/inference/handler_test.go | 27 +++++-
7 files changed, 261 insertions(+), 32 deletions(-)
diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go
index 5af478d9..16a39573 100644
--- a/backend/internal/application/gateway/quality_retry.go
+++ b/backend/internal/application/gateway/quality_retry.go
@@ -133,9 +133,13 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
if sig.HasThinking {
return QualityDeliver
}
- output := sig.OutputTokens
- if output < sig.VisibleTokens {
- output = sig.VisibleTokens
+ // Prefer observed/derived visible output. Total output includes reasoning
+ // tokens, which are deliberately not trusted as quality evidence above. If
+ // the stream exposed no visible count at all, retain OutputTokens as a
+ // compatibility fallback for terminal usage-only responses.
+ output := sig.VisibleTokens
+ if output <= 0 {
+ output = sig.OutputTokens
}
enough := output >= minOutput
if sig.ReasoningStarted && !sig.Terminal && !sig.HoldExpired {
diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go
index b0ffffb4..74a2da85 100644
--- a/backend/internal/application/gateway/quality_retry_scan.go
+++ b/backend/internal/application/gateway/quality_retry_scan.go
@@ -14,11 +14,12 @@ import (
)
const (
- qualityProtocolChat = "chat"
- qualityProtocolResponses = "responses"
- qualityProtocolAnthropic = "anthropic"
- qualityReasoningSSEComment = ": grok2api-reasoning-start"
- qualityHoldMaxBufferBytes = 4 << 20
+ qualityProtocolChat = "chat"
+ qualityProtocolResponses = "responses"
+ qualityProtocolAnthropic = "anthropic"
+ qualityReasoningSSEComment = ": grok2api-reasoning-start"
+ qualityReasoningEvidenceSSEComment = ": grok2api-reasoning-evidence"
+ qualityHoldMaxBufferBytes = 4 << 20
)
type qualityScanState struct {
@@ -175,6 +176,13 @@ func ObserveQualityChunk(state *qualityScanState, chunk []byte) {
state.reasoningStarted = true
continue
}
+ if bytes.Equal(line, []byte(qualityReasoningEvidenceSSEComment)) {
+ // Protocol converters cannot expose encrypted_content in every public
+ // JSON contract. This internal SSE comment preserves that evidence.
+ state.reasoningStarted = true
+ state.hasThinking = true
+ continue
+ }
if !bytes.HasPrefix(line, []byte("data:")) {
continue
}
@@ -238,7 +246,7 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
}
for _, choice := range event.Choices {
delta := choice.Delta
- if delta.Reasoning != "" || delta.ReasoningContent != "" || delta.ThinkingContent != "" {
+ if strings.TrimSpace(delta.Reasoning) != "" || strings.TrimSpace(delta.ReasoningContent) != "" || strings.TrimSpace(delta.ThinkingContent) != "" {
state.hasThinking = true
}
if delta.Content != "" {
@@ -270,14 +278,14 @@ func noteResponsesReasoningItem(state *qualityScanState, item qualityReasoningIt
func observeQualityResponses(state *qualityScanState, payload []byte) {
var event struct {
- Type string `json:"type"`
- Delta string `json:"delta"`
- Item qualityReasoningItem
+ Type string `json:"type"`
+ Delta string `json:"delta"`
+ Item qualityReasoningItem
Response *struct {
ID string `json:"id"`
Model string `json:"model"`
Output []qualityReasoningItem `json:"output"`
- Usage *struct {
+ Usage *struct {
OutputTokens int64 `json:"output_tokens"`
InputTokens int64 `json:"input_tokens"`
TotalTokens int64 `json:"total_tokens"`
@@ -294,7 +302,7 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
case "response.completed", "response.incomplete", "response.failed":
state.terminal = true
case "response.reasoning_text.delta", "response.reasoning_summary_text.delta":
- if event.Delta != "" {
+ if strings.TrimSpace(event.Delta) != "" {
state.hasThinking = true
}
case "response.output_item.added", "response.output_item.done":
@@ -331,9 +339,10 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
Type string `json:"type"`
} `json:"content_block"`
Delta struct {
- Type string `json:"type"`
- Text string `json:"text"`
- Thinking string `json:"thinking"`
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Thinking string `json:"thinking"`
+ Signature string `json:"signature"`
} `json:"delta"`
Usage *struct {
OutputTokens int64 `json:"output_tokens"`
@@ -353,7 +362,13 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
state.reasoningStarted = true
}
case "content_block_delta":
- if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
+ if event.Delta.Type == "thinking_delta" && strings.TrimSpace(event.Delta.Thinking) != "" {
+ state.hasThinking = true
+ }
+ 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.
+ state.reasoningStarted = true
state.hasThinking = true
}
if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index fd7cde61..b9dcbdd5 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -20,6 +20,7 @@ import (
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
+ "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
)
@@ -35,6 +36,7 @@ func TestClassifyQualityHold(t *testing.T) {
{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},
+ {name: "short visible output ignores inflated total", sig: QualityStreamSignals{VisibleTokens: 1, OutputTokens: 80, Terminal: true}, want: QualityDeliver},
{name: "short no think delivers", sig: QualityStreamSignals{VisibleTokens: 10, Terminal: true}, want: QualityDeliver},
{name: "empty terminal waits for transport handling", sig: QualityStreamSignals{Terminal: true}, want: QualityWait},
{name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold},
@@ -265,12 +267,102 @@ func TestObserveQualityChunkShortNoThink(t *testing.T) {
}
}
+func TestObserveQualityChunkShortNoThinkIgnoresFakeReasoningUsage(t *testing.T) {
+ t.Parallel()
+ state := qualityScanState{protocol: qualityProtocolChat}
+ ObserveQualityChunk(&state, []byte(sse(
+ ": grok2api-reasoning-start",
+ `data: {"choices":[{"delta":{"content":"OK"}}]}`,
+ `data: {"usage":{"completion_tokens":80,"completion_tokens_details":{"reasoning_tokens":79}}}`,
+ "data: [DONE]",
+ )))
+ sig := state.signals()
+ if sig.VisibleTokens >= 32 || sig.OutputTokens != 80 || sig.ReasoningTokens != 79 {
+ t.Fatalf("fake-usage short reply signals = %#v", sig)
+ }
+ if got := ClassifyQualityHold(sig, 32); got != QualityDeliver {
+ t.Fatalf("short visible reply must not be withheld by inflated usage: %s (%#v)", got, sig)
+ }
+}
+
+func TestObserveQualityConvertedEncryptedThinking(t *testing.T) {
+ t.Parallel()
+ 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_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}}}}`,
+ )
+ tests := []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}},
+ }
+ for _, test := range tests {
+ 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 {
+ t.Fatalf("converted encrypted thinking evidence was lost:\n%s", converted)
+ }
+ if got := ClassifyQualityHold(sig, 32); got != QualityDeliver {
+ t.Fatalf("converted encrypted thinking verdict = %s (%#v)", got, sig)
+ }
+ })
+ }
+}
+
+func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name string
+ protocol string
+ fixture string
+ }{
+ {name: "chat", protocol: qualityProtocolChat, fixture: sse(`data: {"choices":[{"delta":{"reasoning_content":" \n\t"}}]}`)},
+ {name: "responses", protocol: qualityProtocolResponses, fixture: sse(`data: {"type":"response.reasoning_summary_text.delta","delta":" \n\t"}`)},
+ {name: "messages", protocol: qualityProtocolAnthropic, fixture: sse(`data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":" \n\t"}}`)},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ state := qualityScanState{protocol: test.protocol}
+ ObserveQualityChunk(&state, []byte(test.fixture))
+ if sig := state.signals(); sig.HasThinking {
+ t.Fatalf("whitespace-only reasoning counted as thinking: %#v", sig)
+ }
+ })
+ }
+}
+
+func TestObserveQualityChunkAnthropicSignatureIsThinking(t *testing.T) {
+ t.Parallel()
+ state := qualityScanState{protocol: qualityProtocolAnthropic}
+ ObserveQualityChunk(&state, []byte(sse(
+ `data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"gAAAA-cipher"}}`,
+ )))
+ if sig := state.signals(); !sig.HasThinking || !sig.ReasoningStarted {
+ t.Fatalf("non-empty Anthropic signature must count as encrypted thinking: %#v", sig)
+ }
+}
+
func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) {
t.Parallel()
fake := qualityScanState{protocol: qualityProtocolResponses}
ObserveQualityChunk(&fake, []byte(sse(
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
- `data: {"type":"response.output_text.delta","delta":"hello hello hello hello hello hello hello hello"}`,
+ `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("hello ", 40)+`"}`,
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
)))
fakeSig := fake.signals()
diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go
index 0d0d4134..425cf81c 100644
--- a/backend/internal/infra/provider/conversation/conversation_test.go
+++ b/backend/internal/infra/provider/conversation/conversation_test.go
@@ -928,6 +928,50 @@ func TestConvertResponsesStreamMarksChatReasoningStart(t *testing.T) {
}
}
+func TestConvertResponsesStreamMarksEncryptedChatReasoningEvidence(t *testing.T) {
+ stream := strings.Join([]string{
+ `event: response.created`,
+ `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "",
+ `event: response.output_item.added`,
+ `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, "",
+ `event: response.output_item.done`,
+ `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"signature"}}`, "",
+ `event: response.completed`,
+ `data: {"type":"response.completed","response":{"status":"completed"}}`, "", "",
+ }, "\n")
+ converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
+ if err != nil {
+ 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 {
+ t.Fatalf("encrypted reasoning markers missing or duplicated: %s", text)
+ }
+ if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") {
+ t.Fatalf("encrypted reasoning leaked into Chat JSON: %s", text)
+ }
+}
+
+func TestConvertResponsesStreamMarksFinalEnvelopeReasoningEvidence(t *testing.T) {
+ stream := strings.Join([]string{
+ `event: response.created`,
+ `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "",
+ `event: response.completed`,
+ `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"rs_1","type":"reasoning","encrypted_content":"signature"}]}}`, "", "",
+ }, "\n")
+ converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(converted)
+ if strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 {
+ t.Fatalf("final-envelope reasoning evidence missing or duplicated: %s", text)
+ }
+ if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") {
+ t.Fatalf("final-envelope encrypted reasoning leaked into Chat JSON: %s", text)
+ }
+}
+
func TestConvertResponsesStreamChatPrefersRawReasoningOverSummary(t *testing.T) {
stream := strings.Join([]string{
`event: response.created`,
diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go
index 8180c89f..ad889908 100644
--- a/backend/internal/infra/provider/conversation/stream.go
+++ b/backend/internal/infra/provider/conversation/stream.go
@@ -53,6 +53,7 @@ type streamConverter struct {
thinkingIndex int
thinkingItemID string
chatReasoningMark bool
+ evidenceMarked bool
reasoningItems map[string]*reasoningStreamState
reasoningOrder []string
activeReasoningID string
@@ -95,6 +96,23 @@ 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 {
+ return nil
+ }
+ if err := c.start(); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(c.writer, ": grok2api-reasoning-evidence\n\n"); err != nil {
+ return err
+ }
+ c.evidenceMarked = true
+ return nil
+}
+
// noteWebSearch records a Build web_search_call. Emission is deferred to doneMessages
// so we always use the completed action.sources payload from the final envelope when available.
// For progressive UI we still emit server_tool_use as soon as we see the call.
@@ -314,6 +332,11 @@ func (c *streamConverter) handle(event string, data []byte) error {
return err
}
}
+ if strings.TrimSpace(item.Encrypted) != "" {
+ if err := c.markReasoningEvidence(); err != nil {
+ return err
+ }
+ }
return c.thinkingDone(item)
}
if item.Type == "web_search_call" && c.operation == OperationMessages && c.options.AnthropicWebSearch {
@@ -325,6 +348,13 @@ func (c *streamConverter) handle(event string, data []byte) error {
var response responseEnvelope
_ = json.Unmarshal(root["response"], &response)
c.setResponse(response)
+ for _, item := range response.Output {
+ if item.Type == "reasoning" && strings.TrimSpace(item.Encrypted) != "" {
+ if err := c.markReasoningEvidence(); err != nil {
+ return err
+ }
+ }
+ }
if c.operation == OperationMessages && c.options.AnthropicWebSearch {
parsed := parseResponse(response)
for _, call := range parsed.WebSearch {
diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go
index af803a0f..f2cba625 100644
--- a/backend/internal/transport/http/inference/handler.go
+++ b/backend/internal/transport/http/inference/handler.go
@@ -1288,7 +1288,7 @@ type responseMetadata struct {
func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func()) (responseMetadata, error) {
inspector := &responseInspector{protocol: protocol, onFirstToken: onFirstToken}
- markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat}
+ markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat || protocol == streamProtocolAnthropic}
var compat responsesCompatState
buffer := make([]byte, responseCopyBufferBytes)
received := 0
@@ -1466,13 +1466,13 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte {
if !f.enabled {
return chunk
}
- marker := []byte(reasoningStartSSEComment + "\n\n")
f.pending = append(f.pending, chunk...)
result := make([]byte, 0, len(f.pending))
for {
- if index := bytes.Index(f.pending, marker); index >= 0 {
+ index, markerLength := nextInternalSSEMarker(f.pending)
+ if index >= 0 {
result = append(result, f.pending[:index]...)
- f.pending = f.pending[index+len(marker):]
+ f.pending = f.pending[index+markerLength:]
continue
}
if final {
@@ -1481,11 +1481,13 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte {
return result
}
keep := 0
- limit := min(len(f.pending), len(marker)-1)
- for size := limit; size > 0; size-- {
- if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) {
- keep = size
- break
+ for _, marker := range internalSSEMarkers {
+ limit := min(len(f.pending), len(marker)-1)
+ for size := limit; size > keep; size-- {
+ if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) {
+ keep = size
+ break
+ }
}
}
result = append(result, f.pending[:len(f.pending)-keep]...)
@@ -1494,6 +1496,19 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte {
}
}
+func nextInternalSSEMarker(value []byte) (int, int) {
+ index := -1
+ length := 0
+ for _, marker := range internalSSEMarkers {
+ candidate := bytes.Index(value, marker)
+ if candidate >= 0 && (index < 0 || candidate < index) {
+ index = candidate
+ length = len(marker)
+ }
+ }
+ return index, length
+}
+
func copyJSON(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol) (responseMetadata, error) {
buffer := make([]byte, responseCopyBufferBytes)
metadataBody := make([]byte, 0, responseCopyBufferBytes)
@@ -1545,7 +1560,15 @@ type responseInspector struct {
terminalFailure bool
}
-const reasoningStartSSEComment = ": grok2api-reasoning-start"
+const (
+ reasoningStartSSEComment = ": grok2api-reasoning-start"
+ reasoningEvidenceSSEComment = ": grok2api-reasoning-evidence"
+)
+
+var internalSSEMarkers = [][]byte{
+ []byte(reasoningStartSSEComment + "\n\n"),
+ []byte(reasoningEvidenceSSEComment + "\n\n"),
+}
func (i *responseInspector) Inspect(chunk []byte) {
i.pending = append(i.pending, chunk...)
diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go
index 9215bd34..0164e2da 100644
--- a/backend/internal/transport/http/inference/handler_test.go
+++ b/backend/internal/transport/http/inference/handler_test.go
@@ -927,8 +927,8 @@ func TestStreamInspectorMarksChatReasoningComment(t *testing.T) {
}
func TestInternalSSEMarkerFilterAcrossChunkBoundaries(t *testing.T) {
- marker := reasoningStartSSEComment + "\n\n"
- input := []byte("data: before\n\n" + marker + "data: after\n\n")
+ markers := reasoningStartSSEComment + "\n\n" + reasoningEvidenceSSEComment + "\n\n"
+ input := []byte("data: before\n\n" + markers + "data: after\n\n")
want := "data: before\n\ndata: after\n\n"
for split := 0; split <= len(input); split++ {
filter := internalSSEMarkerFilter{enabled: true}
@@ -948,6 +948,7 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) {
context, _ := gin.CreateTestContext(recorder)
body := `data: {"choices":[{"delta":{"role":"assistant"}}]}` + "\n\n" +
": grok2api-reasoning-start\n\n" +
+ ": grok2api-reasoning-evidence\n\n" +
`data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" +
"data: [DONE]\n\n"
marked := 0
@@ -957,7 +958,7 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) {
if marked != 1 {
t.Fatalf("first token marked %d times", marked)
}
- if strings.Contains(recorder.Body.String(), "grok2api-reasoning-start") {
+ if strings.Contains(recorder.Body.String(), "grok2api-reasoning-") {
t.Fatalf("internal marker leaked to client: %q", recorder.Body.String())
}
if !strings.Contains(recorder.Body.String(), `"content":"hello"`) {
@@ -965,6 +966,26 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) {
}
}
+func TestCopyStreamConsumesAnthropicReasoningEvidenceMarker(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ body := ": grok2api-reasoning-evidence\n\n" +
+ "event: content_block_delta\n" +
+ `data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig"}}` + "\n\n" +
+ "event: message_stop\n" +
+ `data: {"type":"message_stop"}` + "\n\n"
+ if _, err := copyStream(context.Writer, strings.NewReader(body), streamProtocolAnthropic, nil); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(recorder.Body.String(), "grok2api-reasoning-evidence") {
+ t.Fatalf("internal Anthropic marker leaked to client: %q", recorder.Body.String())
+ }
+ if !strings.Contains(recorder.Body.String(), `"signature":"sig"`) {
+ t.Fatalf("Anthropic signature delta missing: %q", recorder.Body.String())
+ }
+}
+
func TestCopyStreamPreservesBufferedTailOnReadError(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
From d93547dc19fbc644fa6fd8d110942fdfa53f1894 Mon Sep 17 00:00:00 2001
From: Chenyme <118253778+chenyme@users.noreply.github.com>
Date: Thu, 20 Aug 2026 15:15:31 +0800
Subject: [PATCH 10/13] fix: avoid replaying hosted tools during quality
retries
---
.../application/gateway/quality_retry.go | 95 ++++++++++++-------
.../application/gateway/quality_retry_test.go | 50 +++++++++-
2 files changed, 110 insertions(+), 35 deletions(-)
diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go
index c1ac2760..9c89cd08 100644
--- a/backend/internal/application/gateway/quality_retry.go
+++ b/backend/internal/application/gateway/quality_retry.go
@@ -270,11 +270,14 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole {
return false
}
- // Grok TUI always declares a tools schema, and after local tools run the
- // next /v1/responses body already contains function_call_output. Retrying
- // that body on another account does not re-execute TUI tools — it only
- // regenerates the model turn. Skipping hold here let 0-thinking dumps
- // through on the common agent loop. Keep holding.
+ // 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.
@@ -287,32 +290,68 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn
return modeldomain.SupportsReasoningForProvider(route.Provider, route.UpstreamModel)
}
-func qualityRequestHasInFlightToolResults(body []byte) bool {
- var payload any
- if json.Unmarshal(body, &payload) != nil {
+func qualityRequestHasReplayUnsafeHostedTools(body []byte) bool {
+ var payload map[string]any
+ if json.Unmarshal(body, &payload) != nil || payload == nil {
return false
}
- return jsonTreeHasInFlightToolResult(payload)
-}
-
-func jsonTreeHasInFlightToolResult(node any) bool {
- switch typed := node.(type) {
- case map[string]any:
- role := jsonNodeString(typed["role"])
- typ := jsonNodeString(typed["type"])
- if role == "tool" || typ == "function_call_output" || typ == "tool_result" || typ == "tool_use_output" {
+ if raw, exists := payload["web_search_options"]; exists && raw != nil {
+ return true
+ }
+ if raw, exists := payload["mcp_servers"]; exists && raw != nil {
+ servers, ok := raw.([]any)
+ if !ok || len(servers) > 0 {
return true
}
- for _, child := range typed {
- if jsonTreeHasInFlightToolResult(child) {
- return true
- }
+ }
+ if qualityToolListHasReplayUnsafeHostedTool(payload["tools"]) {
+ return true
+ }
+ // Responses Tool Search can load declarations later in the request. Only
+ // inspect additional_tools items; arbitrary user/schema objects may also
+ // contain a field named "tools" and must not affect the retry policy.
+ items, _ := payload["input"].([]any)
+ for _, rawItem := range items {
+ item, ok := rawItem.(map[string]any)
+ if !ok || jsonNodeString(item["type"]) != "additional_tools" {
+ continue
}
- case []any:
- for _, child := range typed {
- if jsonTreeHasInFlightToolResult(child) {
+ if qualityToolListHasReplayUnsafeHostedTool(item["tools"]) {
+ return true
+ }
+ }
+ return false
+}
+
+func qualityToolListHasReplayUnsafeHostedTool(value any) bool {
+ tools, ok := value.([]any)
+ if !ok {
+ return false
+ }
+ for _, rawTool := range tools {
+ tool, ok := rawTool.(map[string]any)
+ if !ok {
+ continue
+ }
+ kind := jsonNodeString(tool["type"])
+ switch kind {
+ case "", "function", "custom", "local_shell", "apply_patch", "tool_search":
+ // These declarations only ask the model to return a call. Execution
+ // happens in the client after the held response is committed.
+ continue
+ case "shell":
+ environment, _ := tool["environment"].(map[string]any)
+ if jsonNodeString(environment["type"]) != "local" {
return true
}
+ case "namespace":
+ if qualityToolListHasReplayUnsafeHostedTool(tool["tools"]) {
+ return true
+ }
+ default:
+ // Default to no replay for every server/native tool, including types
+ // added by future protocol versions that this gateway does not know yet.
+ return true
}
}
return false
@@ -347,14 +386,6 @@ func qualityRequestDisablesReasoning(body []byte) bool {
return jsonStringEquals(payload["thinking"], "disabled")
}
-func nonEmptyJSONCollection(raw json.RawMessage) bool {
- trimmed := strings.TrimSpace(string(raw))
- if trimmed == "" || trimmed == "null" || trimmed == "[]" || trimmed == "{}" {
- return false
- }
- return strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "{")
-}
-
func jsonStringEquals(raw json.RawMessage, want string) bool {
var value string
return json.Unmarshal(raw, &value) == nil && strings.EqualFold(strings.TrimSpace(value), want)
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index f2c2a52f..33cf59b7 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -576,6 +576,10 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
{name: "client tools schema", body: `{"tools":[{"type":"function","function":{"name":"charge"}}]}`},
{name: "legacy functions schema", body: `{"functions":[{"name":"charge"}]}`},
{name: "tui tools schema plus user input", body: `{"model":"grok-4.6","tools":[{"type":"function","name":"read_file"}],"input":[{"role":"user","content":"hello"}]}`},
+ {name: "local shell declaration", body: `{"tools":[{"type":"local_shell"}]}`},
+ {name: "local environment shell declaration", body: `{"tools":[{"type":"shell","environment":{"type":"local"}}]}`},
+ {name: "apply patch declaration", body: `{"tools":[{"type":"apply_patch"}]}`},
+ {name: "client namespace", body: `{"tools":[{"type":"namespace","name":"local","tools":[{"type":"function","name":"read_file"}]}]}`},
} {
t.Run(test.name, func(t *testing.T) {
request := input
@@ -596,14 +600,54 @@ func TestShouldHoldQualityStreamGates(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
request := input
request.Body = []byte(test.body)
- if !qualityRequestHasInFlightToolResults(request.Body) {
- t.Fatal("fixture must still be detected as tool output")
- }
if !shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) {
t.Fatal("in-flight tool results must still be held so 0-thinking agent turns are classified")
}
})
}
+ for _, test := range []struct {
+ name string
+ body string
+ }{
+ {name: "responses web search", body: `{"tools":[{"type":"web_search"}]}`},
+ {name: "versioned web search", body: `{"tools":[{"type":"web_search_2025_08_26"}]}`},
+ {name: "x search", body: `{"tools":[{"type":"x_search"}]}`},
+ {name: "image generation", body: `{"tools":[{"type":"image_generation"}]}`},
+ {name: "file search", body: `{"tools":[{"type":"file_search"}]}`},
+ {name: "collections search", body: `{"tools":[{"type":"collections_search"}]}`},
+ {name: "code execution", body: `{"tools":[{"type":"code_execution"}]}`},
+ {name: "code interpreter", body: `{"tools":[{"type":"code_interpreter"}]}`},
+ {name: "hosted shell", body: `{"tools":[{"type":"shell","environment":{"type":"container_auto"}}]}`},
+ {name: "future native tool skips replay", body: `{"tools":[{"type":"future_server_tool"}]}`},
+ {name: "remote mcp", body: `{"tools":[{"type":"mcp","server_url":"https://example.com"}]}`},
+ {name: "mixed client and hosted", body: `{"tools":[{"type":"function","name":"read_file"},{"type":"web_search"}]}`},
+ {name: "chat web search options", body: `{"web_search_options":{}}`},
+ {name: "messages web search", body: `{"tools":[{"type":"web_search_20250305","name":"web_search"}]}`},
+ {name: "messages mcp servers", body: `{"mcp_servers":[{"type":"url","url":"https://example.com"}]}`},
+ {name: "deferred hosted tool", body: `{"input":[{"type":"additional_tools","tools":[{"type":"mcp","server_url":"https://example.com"}]}]}`},
+ {name: "nested hosted tool", body: `{"tools":[{"type":"namespace","name":"remote","tools":[{"type":"web_search"}]}]}`},
+ {name: "after local tool with hosted declaration", body: `{"tools":[{"type":"web_search"}],"input":[{"type":"function_call_output","call_id":"call_1","output":"done"}]}`},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ request := input
+ request.Body = []byte(test.body)
+ 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")
+ }
+ })
+ }
+ for _, body := range []string{
+ `{"tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"tools":{"type":"array"}}}}]}`,
+ `{"mcp_servers":[]}`,
+ `{"web_search_options":null}`,
+ } {
+ if qualityRequestHasReplayUnsafeHostedTools([]byte(body)) {
+ t.Fatalf("safe or empty tool metadata classified as hosted: %s", body)
+ }
+ }
toolCache := input
toolCache.Body = []byte(`{"messages":[{"role":"user","content":"hello"}]}`)
toolCache.AllowClientToolCacheRoute = true
From a2f2687b33faa586890e6ab88b2c96a8c826bf12 Mon Sep 17 00:00:00 2001
From: Chenyme <118253778+chenyme@users.noreply.github.com>
Date: Thu, 20 Aug 2026 15:32:25 +0800
Subject: [PATCH 11/13] fix: retry terminal empty streams without
misclassifying tool output
---
.../application/gateway/quality_retry_scan.go | 104 ++++++++--
.../application/gateway/quality_retry_test.go | 185 ++++++++++++++----
2 files changed, 240 insertions(+), 49 deletions(-)
diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go
index 0d57a530..68381de0 100644
--- a/backend/internal/application/gateway/quality_retry_scan.go
+++ b/backend/internal/application/gateway/quality_retry_scan.go
@@ -25,6 +25,8 @@ type qualityScanState struct {
pending []byte
hasThinking bool
visibleRunes int
+ aggregateRunes int
+ semanticOutput bool
reasoningTokens int64
outputTokens int64
usage Usage
@@ -124,7 +126,8 @@ func qualityProtocolForOperation(operation audit.Operation) string {
}
func (s *qualityScanState) signals() QualityStreamSignals {
- visible := int64((s.visibleRunes + 3) / 4)
+ visibleRunes := max(s.visibleRunes, s.aggregateRunes)
+ visible := int64((visibleRunes + 3) / 4)
if s.usage.Reported {
fromUsage := s.usage.OutputTokens - s.usage.ReasoningTokens
if fromUsage > visible {
@@ -201,6 +204,8 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
Reasoning string `json:"reasoning"`
ReasoningContent string `json:"reasoning_content"`
ThinkingContent string `json:"thinking_content"`
+ ToolCalls []any `json:"tool_calls"`
+ FunctionCall any `json:"function_call"`
} `json:"delta"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
@@ -240,24 +245,35 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
if delta.Content != "" {
noteVisibleContent(state, delta.Content)
}
+ if len(delta.ToolCalls) > 0 || delta.FunctionCall != nil {
+ state.semanticOutput = true
+ }
if choice.FinishReason != "" {
state.terminal = true
}
}
}
+type qualityResponsesOutputItem struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Content []struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Refusal string `json:"refusal"`
+ } `json:"content"`
+}
+
func observeQualityResponses(state *qualityScanState, payload []byte) {
var event struct {
- Type string `json:"type"`
- Delta string `json:"delta"`
- Item struct {
- ID string `json:"id"`
- Type string `json:"type"`
- } `json:"item"`
+ Type string `json:"type"`
+ Delta string `json:"delta"`
+ Item qualityResponsesOutputItem `json:"item"`
Response *struct {
- ID string `json:"id"`
- Model string `json:"model"`
- Usage *struct {
+ ID string `json:"id"`
+ Model string `json:"model"`
+ Output []qualityResponsesOutputItem `json:"output"`
+ Usage *struct {
OutputTokens int64 `json:"output_tokens"`
InputTokens int64 `json:"input_tokens"`
TotalTokens int64 `json:"total_tokens"`
@@ -281,10 +297,17 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
if event.Item.Type == "reasoning" && event.Item.ID != "" {
state.hasThinking = true
}
+ state.aggregateRunes = max(state.aggregateRunes, observeQualityResponsesOutputItem(state, event.Item))
+ case "response.output_item.done":
+ state.aggregateRunes = max(state.aggregateRunes, observeQualityResponsesOutputItem(state, event.Item))
case "response.output_text.delta":
if event.Delta != "" {
noteVisibleContent(state, event.Delta)
}
+ case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta", "response.mcp_call_arguments.delta":
+ if event.Delta != "" {
+ state.semanticOutput = true
+ }
}
if event.Response != nil {
if state.responseID == "" {
@@ -303,19 +326,57 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
state.hasThinking = true
}
}
+ aggregateRunes := 0
+ for _, item := range event.Response.Output {
+ aggregateRunes += observeQualityResponsesOutputItem(state, item)
+ }
+ state.aggregateRunes = max(state.aggregateRunes, aggregateRunes)
}
}
+func observeQualityResponsesOutputItem(state *qualityScanState, item qualityResponsesOutputItem) int {
+ if state == nil {
+ return 0
+ }
+ visibleRunes := 0
+ switch item.Type {
+ case "", "reasoning":
+ return 0
+ case "message":
+ for _, content := range item.Content {
+ text := content.Text
+ if text == "" {
+ text = content.Refusal
+ }
+ if text != "" {
+ visibleRunes += utf8.RuneCountInString(text)
+ state.semanticOutput = true
+ continue
+ }
+ if content.Type != "" && content.Type != "output_text" && content.Type != "refusal" {
+ state.semanticOutput = true
+ }
+ }
+ default:
+ // Function, shell, MCP and other call items are meaningful output even
+ // when the provider omits usage and argument-delta events.
+ state.semanticOutput = true
+ }
+ return visibleRunes
+}
+
func observeQualityAnthropic(state *qualityScanState, payload []byte) {
var event struct {
Type string `json:"type"`
ContentBlock struct {
Type string `json:"type"`
+ Text string `json:"text"`
} `json:"content_block"`
Delta struct {
- Type string `json:"type"`
- Text string `json:"text"`
- Thinking string `json:"thinking"`
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Thinking string `json:"thinking"`
+ PartialJSON string `json:"partial_json"`
} `json:"delta"`
Usage *struct {
OutputTokens int64 `json:"output_tokens"`
@@ -331,8 +392,17 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
case "message_stop":
state.terminal = true
case "content_block_start":
- if event.ContentBlock.Type == "thinking" {
+ switch event.ContentBlock.Type {
+ case "thinking", "redacted_thinking":
state.hasThinking = true
+ case "text":
+ if event.ContentBlock.Text != "" {
+ noteVisibleContent(state, event.ContentBlock.Text)
+ state.semanticOutput = true
+ }
+ case "":
+ default:
+ state.semanticOutput = true
}
case "content_block_delta":
if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
@@ -341,6 +411,9 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
noteVisibleContent(state, event.Delta.Text)
}
+ if event.Delta.Type == "input_json_delta" && event.Delta.PartialJSON != "" {
+ state.semanticOutput = true
+ }
}
if event.Usage != nil {
state.usage.Reported = true
@@ -427,6 +500,9 @@ func finishQualityPeek(held *bytes.Buffer, pump *qualityReadPump, state *quality
state.terminal = true
signals := state.signals()
if !signals.HasThinking && signals.ReasoningTokens <= 0 && signals.OutputTokens <= 0 && signals.VisibleTokens <= 0 {
+ if state.semanticOutput {
+ return newPrefixReplay(held, pump), QualityDeliver, state.usage, state.responseID, nil
+ }
return newPrefixReplay(held, pump), QualityWait, state.usage, state.responseID, errQualityEmptyStream
}
return newPrefixReplay(held, pump), ClassifyQualityHold(signals, cfg.MinOutputTokens), state.usage, state.responseID, nil
diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go
index a37aad1a..d5072d3c 100644
--- a/backend/internal/application/gateway/quality_retry_test.go
+++ b/backend/internal/application/gateway/quality_retry_test.go
@@ -461,45 +461,160 @@ func TestPeekQualityStreamHoldTimeoutEmptyDoesNotFailOpen(t *testing.T) {
}
}
+type qualityOpenPeekResult struct {
+ replay io.ReadCloser
+ verdict QualityVerdict
+ err error
+}
+
+func peekOpenQualityStreamForTest(t *testing.T, protocol, stream string) qualityOpenPeekResult {
+ t.Helper()
+ reader, writer := io.Pipe()
+ done := make(chan qualityOpenPeekResult, 1)
+ go func() {
+ replay, verdict, _, _, err := peekQualityStream(
+ context.Background(), reader, protocol,
+ QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: 2 * time.Second},
+ )
+ done <- qualityOpenPeekResult{replay: replay, verdict: verdict, err: err}
+ }()
+ if _, err := io.WriteString(writer, stream); err != nil {
+ _ = writer.Close()
+ t.Fatal(err)
+ }
+ select {
+ case result := <-done:
+ _ = writer.Close()
+ return result
+ case <-time.After(500 * time.Millisecond):
+ _ = writer.CloseWithError(errors.New("test terminal stream timeout"))
+ result := <-done
+ if result.replay != nil {
+ _ = result.replay.Close()
+ }
+ t.Fatal("terminal stream waited for hold/idle instead of finishing while the connection remained open")
+ return qualityOpenPeekResult{}
+ }
+}
+
func TestPeekQualityStreamEmptyCompletedRetriesWithoutIdle(t *testing.T) {
t.Parallel()
- started := time.Now()
- replay, verdict, _, _, err := peekQualityStream(
- context.Background(),
- io.NopCloser(strings.NewReader(sse(
- `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":0}}}`,
- ))),
- qualityProtocolResponses,
- QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: 2 * time.Second},
- )
- if replay != nil {
- defer replay.Close()
- }
- if !errors.Is(err, errQualityEmptyStream) {
- t.Fatalf("peek error = %v, want empty stream", err)
- }
- if verdict != QualityWait {
- t.Fatalf("verdict = %s, want wait so the attempt loop retries as transport", verdict)
- }
- if time.Since(started) > 500*time.Millisecond {
- t.Fatalf("empty completed stream waited %s, want immediate retry", time.Since(started))
+ for _, test := range []struct {
+ name string
+ protocol string
+ stream string
+ }{
+ {
+ name: "responses completed",
+ protocol: qualityProtocolResponses,
+ stream: sse(
+ `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":0}}}`,
+ ),
+ },
+ {
+ name: "responses completed with empty text node",
+ protocol: qualityProtocolResponses,
+ stream: sse(
+ `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":""}]}],"usage":{"output_tokens":0}}}`,
+ ),
+ },
+ {name: "chat done", protocol: qualityProtocolChat, stream: sse("data: [DONE]")},
+ {
+ name: "chat finish reason",
+ protocol: qualityProtocolChat,
+ stream: sse(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`),
+ },
+ {name: "anthropic message stop", protocol: qualityProtocolAnthropic, stream: sse(`data: {"type":"message_stop"}`)},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ result := peekOpenQualityStreamForTest(t, test.protocol, test.stream)
+ if result.replay != nil {
+ defer result.replay.Close()
+ }
+ if !errors.Is(result.err, errQualityEmptyStream) {
+ t.Fatalf("peek error = %v, want empty stream", result.err)
+ }
+ if result.verdict != QualityWait {
+ t.Fatalf("verdict = %s, want wait so the attempt loop retries as transport", result.verdict)
+ }
+ })
}
+}
- started = time.Now()
- replay, verdict, _, _, err = peekQualityStream(
- context.Background(),
- io.NopCloser(strings.NewReader(sse("data: [DONE]"))),
- qualityProtocolChat,
- QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: 2 * time.Second},
- )
- if replay != nil {
- defer replay.Close()
- }
- if !errors.Is(err, errQualityEmptyStream) {
- t.Fatalf("chat empty [DONE] peek error = %v, want empty stream", err)
- }
- if time.Since(started) > 500*time.Millisecond {
- t.Fatalf("empty chat [DONE] waited %s, want immediate retry", time.Since(started))
+func TestPeekQualityStreamTerminalSemanticOutputIsNotEmpty(t *testing.T) {
+ t.Parallel()
+ longText := strings.Repeat("word ", 40)
+ shortText := strings.Repeat("a", 80)
+ for _, test := range []struct {
+ name string
+ protocol string
+ stream string
+ wantVerdict QualityVerdict
+ }{
+ {
+ name: "responses aggregate function call",
+ protocol: qualityProtocolResponses,
+ stream: sse(
+ `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}]}}`,
+ ),
+ wantVerdict: QualityDeliver,
+ },
+ {
+ name: "responses streamed function call",
+ protocol: qualityProtocolResponses,
+ stream: sse(
+ `data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","name":"read_file","arguments":""}}`,
+ `data: {"type":"response.completed","response":{"id":"resp_1","output":[]}}`,
+ ),
+ wantVerdict: QualityDeliver,
+ },
+ {
+ name: "chat tool call",
+ protocol: qualityProtocolChat,
+ stream: sse(
+ `data: {"choices":[{"delta":{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}`,
+ ),
+ wantVerdict: QualityDeliver,
+ },
+ {
+ name: "anthropic tool use",
+ protocol: qualityProtocolAnthropic,
+ stream: sse(
+ `data: {"type":"content_block_start","content_block":{"type":"tool_use","id":"tool_1","name":"read_file","input":{}}}`,
+ `data: {"type":"message_stop"}`,
+ ),
+ wantVerdict: QualityDeliver,
+ },
+ {
+ name: "responses aggregate long text",
+ protocol: qualityProtocolResponses,
+ stream: sse(
+ `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"` + longText + `"}]}]}}`,
+ ),
+ wantVerdict: QualityWithhold,
+ },
+ {
+ name: "responses aggregate does not double count deltas",
+ protocol: qualityProtocolResponses,
+ stream: sse(
+ `data: {"type":"response.output_text.delta","delta":"`+shortText+`"}`,
+ `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"`+shortText+`"}]}]}}`,
+ ),
+ wantVerdict: QualityDeliver,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ result := peekOpenQualityStreamForTest(t, test.protocol, test.stream)
+ if result.replay != nil {
+ defer result.replay.Close()
+ }
+ if result.err != nil {
+ t.Fatalf("peek error = %v, want semantic output", result.err)
+ }
+ if result.verdict != test.wantVerdict {
+ t.Fatalf("verdict = %s, want %s", result.verdict, test.wantVerdict)
+ }
+ })
}
}
From 0fb3a04124c9e7491d9c77d8b5feb1971599c47a Mon Sep 17 00:00:00 2001
From: Chenyme <118253778+chenyme@users.noreply.github.com>
Date: Thu, 20 Aug 2026 16:09:58 +0800
Subject: [PATCH 12/13] fix: preserve quality strikes when clearing cooldown
---
.../internal/application/account/service.go | 27 +++---
.../transport/http/account/handler.go | 2 +-
.../transport/http/account/handler_test.go | 82 ++++++++++++++++++-
.../src/features/accounts/accounts-api.ts | 2 +-
.../src/features/accounts/accounts-page.tsx | 2 +-
5 files changed, 99 insertions(+), 16 deletions(-)
diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go
index 7a4bb35f..12646137 100644
--- a/backend/internal/application/account/service.go
+++ b/backend/internal/application/account/service.go
@@ -186,6 +186,10 @@ type View struct {
QuotaWindows []accountdomain.QuotaWindow
BuildBotFlagged bool
BuildBotFlagSource int
+ // EnabledChanged is request-scoped update metadata. It is not persisted or
+ // serialized directly; the HTTP layer uses it to avoid warning when a PATCH
+ // merely repeats the account's existing enabled value.
+ EnabledChanged bool
}
type UpdateInput struct {
@@ -2207,6 +2211,7 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie
if err != nil {
return View{}, mapRepositoryError(err)
}
+ enabledChanged := input.Enabled != nil && value.Enabled != *input.Enabled
if input.Name != nil {
value.Name = strings.TrimSpace(*input.Name)
if value.Name == "" {
@@ -2276,7 +2281,12 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie
} else if updated.Enabled && s.providers != nil && s.providers.SupportsCredentialRefresh(updated.Provider) {
s.WakeCredentialRefresh()
}
- return s.Get(ctx, updated.ID)
+ view, err := s.Get(ctx, updated.ID)
+ if err != nil {
+ return View{}, err
+ }
+ view.EnabledChanged = enabledChanged
+ return view, nil
}
// ClearCooldown resets request-path health so a cooled account can be
@@ -2287,17 +2297,14 @@ func (s *Service) ClearCooldown(ctx context.Context, id uint64) (View, error) {
if err != nil {
return View{}, mapRepositoryError(err)
}
- if err := s.accounts.UpdateHealth(ctx, value.ID, value.Provider, 0, nil, "", false); err != nil {
+ // missing_thinking is a durable quality strike, not a transient cooldown
+ // error. Clearing the timer must not turn the next miss into another first
+ // strike and bypass the second-miss disable policy.
+ healthMarker := accountdomain.NormalizeHealthMarker(value.LastError)
+ if err := s.accounts.UpdateHealth(ctx, value.ID, value.Provider, 0, nil, healthMarker, false); err != nil {
return View{}, mapRepositoryError(err)
}
- updated, err := s.accounts.Get(ctx, id)
- if err != nil {
- return View{}, mapRepositoryError(err)
- }
- return View{
- Credential: updated,
- Quota: QuotaView{Type: QuotaTypeUnknown, Source: "unknown", Status: QuotaStatusActive},
- }, nil
+ return s.Get(ctx, id)
}
// MarkBuildAPIFallback 幂等写入 Build 账号 XAI 推理回退标记;失败不吞掉,调用方可重试。
diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go
index c3ec991a..1f67d595 100644
--- a/backend/internal/transport/http/account/handler.go
+++ b/backend/internal/transport/http/account/handler.go
@@ -1259,7 +1259,7 @@ func (h *Handler) update(c *gin.Context) {
return
}
result := newAccountResponse(value)
- if request.Enabled != nil && result.CooldownUntil != nil && time.Now().UTC().Before(*result.CooldownUntil) {
+ if value.EnabledChanged && result.CooldownUntil != nil && time.Now().UTC().Before(*result.CooldownUntil) {
result.EnabledDoesNotClearCooldown = true
}
if request.BuildSuperEntitled != nil {
diff --git a/backend/internal/transport/http/account/handler_test.go b/backend/internal/transport/http/account/handler_test.go
index 5030f767..18d96901 100644
--- a/backend/internal/transport/http/account/handler_test.go
+++ b/backend/internal/transport/http/account/handler_test.go
@@ -19,11 +19,14 @@ import (
accountapp "github.com/chenyme/grok2api/backend/internal/application/account"
accountsyncapp "github.com/chenyme/grok2api/backend/internal/application/accountsync"
+ gatewayapp "github.com/chenyme/grok2api/backend/internal/application/gateway"
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
cliprovider "github.com/chenyme/grok2api/backend/internal/infra/provider/cli"
+ "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
"github.com/chenyme/grok2api/backend/internal/infra/security"
+ "github.com/chenyme/grok2api/backend/internal/repository"
"github.com/gin-gonic/gin"
)
@@ -237,6 +240,10 @@ func TestClearCooldownResetsHealthAndSelectorCache(t *testing.T) {
t.Fatal(err)
}
repo := relational.NewAccountRepository(database)
+ selector := gatewayapp.NewSelector(repo, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute)
+ repo.SetInvalidationObserver(func(_ context.Context, event repository.InvalidationEvent) {
+ selector.ApplyInvalidation(event)
+ })
until := time.Now().UTC().Add(24 * time.Hour)
created, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{
Provider: accountdomain.ProviderBuild, Name: "cooled", SourceKey: "cooled",
@@ -246,10 +253,19 @@ func TestClearCooldownResetsHealthAndSelectorCache(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := repo.UpdateHealth(ctx, created.ID, created.Provider, 3, &until, "upstream status 504", false); err != nil {
+ if err := repo.SaveBilling(ctx, accountdomain.Billing{
+ AccountID: created.ID, PlanCode: "pro", PlanName: "Pro", MonthlyLimit: 100, Used: 25, SyncedAt: time.Now().UTC(),
+ }); err != nil {
t.Fatal(err)
}
- service := accountapp.NewService(repo, nil, nil, nil, nil, nil, nil)
+ if err := repo.UpdateHealth(ctx, created.ID, created.Provider, 3, &until, accountdomain.LastErrorMissingThinking, false); err != nil {
+ t.Fatal(err)
+ }
+ if lease, acquireErr := selector.Acquire(ctx, accountdomain.ProviderBuild, 0, "grok-test", "", "", map[uint64]bool{}, false); acquireErr == nil {
+ lease.Release()
+ t.Fatal("cooled account was schedulable before clear")
+ }
+ service := accountapp.NewService(repo, relational.NewAuditRepository(database), nil, nil, nil, nil, nil)
handler := NewHandler(service, nil)
recorder := httptest.NewRecorder()
@@ -266,14 +282,28 @@ func TestClearCooldownResetsHealthAndSelectorCache(t *testing.T) {
if !strings.Contains(recorder.Body.String(), `"failureCount":0`) {
t.Fatalf("failureCount not reset: %s", recorder.Body.String())
}
+ if !strings.Contains(recorder.Body.String(), `"lastError":"missing_thinking"`) {
+ t.Fatalf("missing-thinking strike was cleared: %s", recorder.Body.String())
+ }
+ if !strings.Contains(recorder.Body.String(), `"planCode":"pro"`) || !strings.Contains(recorder.Body.String(), `"billing"`) {
+ t.Fatalf("complete account view was not returned: %s", recorder.Body.String())
+ }
stored, err := repo.Get(ctx, created.ID)
if err != nil {
t.Fatal(err)
}
- if stored.FailureCount != 0 || stored.CooldownUntil != nil || stored.LastError != "" {
+ if stored.FailureCount != 0 || stored.CooldownUntil != nil || stored.LastError != accountdomain.LastErrorMissingThinking {
t.Fatalf("persisted health = failure=%d cooldown=%v last=%q", stored.FailureCount, stored.CooldownUntil, stored.LastError)
}
+ lease, err := selector.Acquire(ctx, accountdomain.ProviderBuild, 0, "grok-test", "", "", map[uint64]bool{}, false)
+ if err != nil {
+ t.Fatalf("account remained unavailable in selector after clear: %v", err)
+ }
+ if lease.Credential.ID != created.ID || lease.Credential.LastError != accountdomain.LastErrorMissingThinking {
+ t.Fatalf("lease credential = %#v", lease.Credential)
+ }
+ lease.Release()
missing := httptest.NewRecorder()
missingCtx, _ := gin.CreateTestContext(missing)
@@ -285,6 +315,52 @@ func TestClearCooldownResetsHealthAndSelectorCache(t *testing.T) {
}
}
+func TestUpdateCooldownWarningRequiresEnabledChange(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ ctx := context.Background()
+ database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "update-cooldown-warning.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer database.Close()
+ if err := database.InitializeSchema(ctx); err != nil {
+ t.Fatal(err)
+ }
+ repo := relational.NewAccountRepository(database)
+ created, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{
+ Provider: accountdomain.ProviderBuild, Name: "cooled", SourceKey: "cooled-warning",
+ EncryptedAccessToken: "token", Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
+ Priority: 100, MaxConcurrent: 1,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ until := time.Now().UTC().Add(time.Hour)
+ if err := repo.UpdateHealth(ctx, created.ID, created.Provider, 1, &until, "upstream status 504", false); err != nil {
+ t.Fatal(err)
+ }
+ handler := NewHandler(accountapp.NewService(repo, relational.NewAuditRepository(database), nil, nil, nil, nil, nil), nil)
+
+ update := func(body string) *httptest.ResponseRecorder {
+ recorder := httptest.NewRecorder()
+ ginContext, _ := gin.CreateTestContext(recorder)
+ ginContext.Params = []gin.Param{{Key: "id", Value: strconv.FormatUint(created.ID, 10)}}
+ ginContext.Request = httptest.NewRequest("PATCH", "/api/admin/v1/accounts/"+strconv.FormatUint(created.ID, 10), strings.NewReader(body))
+ ginContext.Request.Header.Set("Content-Type", "application/json")
+ handler.update(ginContext)
+ return recorder
+ }
+
+ same := update(`{"enabled":true}`)
+ if same.Code != http.StatusOK || strings.Contains(same.Body.String(), `"enabledDoesNotClearCooldown":true`) {
+ t.Fatalf("unchanged enabled warning: status=%d body=%s", same.Code, same.Body.String())
+ }
+ changed := update(`{"enabled":false}`)
+ if changed.Code != http.StatusOK || !strings.Contains(changed.Body.String(), `"enabledDoesNotClearCooldown":true`) {
+ t.Fatalf("changed enabled warning missing: status=%d body=%s", changed.Code, changed.Body.String())
+ }
+}
+
func (s *accountSynchronizerStub) Sync(_ context.Context, accountIDs ...uint64) accountsyncapp.Result {
s.accountIDs = append(s.accountIDs, accountIDs...)
return accountsyncapp.Result{Succeeded: len(accountIDs)}
diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts
index 9de174ce..02cb10e3 100644
--- a/frontend/src/features/accounts/accounts-api.ts
+++ b/frontend/src/features/accounts/accounts-api.ts
@@ -124,7 +124,7 @@ export type LinkedAccountDTO = {
export type AccountUpdateInput = {
name: string;
- enabled: boolean;
+ enabled?: boolean;
priority: number;
maxConcurrent: number;
minimumRemaining: number;
diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx
index 4e40f8a3..7d1ef40b 100644
--- a/frontend/src/features/accounts/accounts-page.tsx
+++ b/frontend/src/features/accounts/accounts-page.tsx
@@ -325,11 +325,11 @@ export function AccountsPage() {
if (!editing) throw new Error(t("errors.generic"));
const input: AccountUpdateInput = {
name: values.name,
- enabled: values.enabled,
priority: values.priority,
maxConcurrent: values.maxConcurrent,
minimumRemaining: values.minimumRemaining,
};
+ if (values.enabled !== editing.enabled) input.enabled = values.enabled;
if (editing.provider !== "grok_build") {
if (values.clearCloudflareCookies) input.clearCloudflareCookies = true;
else if (values.cloudflareCookies.trim()) input.cloudflareCookies = values.cloudflareCookies;
From 868b836ae5d56a37fdb4933d269839973066c951 Mon Sep 17 00:00:00 2001
From: Chenyme <118253778+chenyme@users.noreply.github.com>
Date: Thu, 20 Aug 2026 16:30:52 +0800
Subject: [PATCH 13/13] fix: emit protocol-safe response.failed events for
empty streams
---
.../transport/http/inference/handler.go | 24 ++++---
.../transport/http/inference/handler_test.go | 64 ++++++++++++++++---
2 files changed, 72 insertions(+), 16 deletions(-)
diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go
index a8b09ba3..e1527070 100644
--- a/backend/internal/transport/http/inference/handler.go
+++ b/backend/internal/transport/http/inference/handler.go
@@ -1151,7 +1151,7 @@ func (h *Handler) handleCreate(c *gin.Context, compact bool) {
writeGatewayError(c, err)
return
}
- h.writeResult(c, result, request.Stream && !compact, streamProtocolResponses)
+ h.writeResponsesResult(c, result, request.Stream && !compact, request.Model)
}
func isJSONRequest(c *gin.Context) bool {
@@ -1211,14 +1211,18 @@ func (h *Handler) handleOwnedResource(c *gin.Context, deleteResource bool) {
}
func (h *Handler) writeResult(c *gin.Context, result *gateway.Result, stream bool, protocol streamProtocol) {
- h.writeProtocolResult(c, result, stream, false, protocol)
+ h.writeProtocolResult(c, result, stream, false, protocol, "")
+}
+
+func (h *Handler) writeResponsesResult(c *gin.Context, result *gateway.Result, stream bool, fallbackModel string) {
+ h.writeProtocolResult(c, result, stream, false, streamProtocolResponses, fallbackModel)
}
func (h *Handler) writeAnthropicResult(c *gin.Context, result *gateway.Result, stream bool) {
- h.writeProtocolResult(c, result, stream, true, streamProtocolAnthropic)
+ h.writeProtocolResult(c, result, stream, true, streamProtocolAnthropic, "")
}
-func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, stream, anthropic bool, protocol streamProtocol) {
+func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, stream, anthropic bool, protocol streamProtocol, fallbackModel string) {
usage := gateway.Usage{}
responseID := ""
errorCode := ""
@@ -1250,7 +1254,7 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st
}
var err error
if stream {
- metadata, copyErr := copyStream(c.Writer, result.Body, protocol, result.MarkFirstToken)
+ metadata, copyErr := copyStreamWithFallbackModel(c.Writer, result.Body, protocol, result.MarkFirstToken, fallbackModel)
usage, responseID, err = metadata.Usage, metadata.ResponseID, copyErr
if metadata.StreamFailure != nil && result.RecordStreamFailure != nil {
result.RecordStreamFailure(*metadata.StreamFailure)
@@ -1287,9 +1291,14 @@ type responseMetadata struct {
}
func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func()) (responseMetadata, error) {
+ return copyStreamWithFallbackModel(writer, source, protocol, onFirstToken, "")
+}
+
+func copyStreamWithFallbackModel(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func(), fallbackModel string) (responseMetadata, error) {
inspector := &responseInspector{protocol: protocol, onFirstToken: onFirstToken}
markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat}
var compat responsesCompatState
+ compat.model = strings.TrimSpace(fallbackModel)
buffer := make([]byte, responseCopyBufferBytes)
received := 0
transferred := 0
@@ -1435,9 +1444,8 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad
"model": model,
"output": []any{},
"error": map[string]any{
- "code": code,
- "message": message,
- "type": "server_error",
+ "code": "server_error",
+ "message": code + ": " + message,
},
}
event := map[string]any{
diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go
index 0d526d64..fd7af0b1 100644
--- a/backend/internal/transport/http/inference/handler_test.go
+++ b/backend/internal/transport/http/inference/handler_test.go
@@ -991,14 +991,14 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) {
want []string
}{
{name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_stream_idle_timeout"`, "data: [DONE]"}},
- {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.failed"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"code":"upstream_stream_idle_timeout"`, `"status":"failed"`, `"model":`}},
+ {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.failed"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"code":"server_error"`, `"message":"upstream_stream_idle_timeout:`, `"status":"failed"`, `"model":"grok-test"`}},
{name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, "上游流式响应长时间无数据"}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
- _, err := copyStream(context.Writer, &idleErrorReader{}, test.protocol, nil)
+ _, err := copyStreamWithFallbackModel(context.Writer, &idleErrorReader{}, test.protocol, nil, "grok-test")
if !errors.Is(err, errUpstreamStreamRead) || !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) {
t.Fatalf("copy error = %v", err)
}
@@ -1094,24 +1094,24 @@ func TestCopyStreamWritesTerminalOnIncompleteEOF(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
- _, err := copyStream(context.Writer, strings.NewReader(""), streamProtocolResponses, nil)
+ _, err := copyStreamWithFallbackModel(context.Writer, strings.NewReader(""), streamProtocolResponses, nil, "grok-test")
if !errors.Is(err, errUpstreamStreamIncomplete) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
- if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"code":"upstream_stream_incomplete"`) {
+ if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"code":"server_error"`) || !strings.Contains(got, `"message":"upstream_stream_incomplete:`) || !strings.Contains(got, `"model":"grok-test"`) {
t.Fatalf("incomplete EOF missing terminal SSE event: %q", got)
}
}
func TestSanitizeResponsesFillsMissingIDs(t *testing.T) {
- state := &responsesCompatState{}
+ state := &responsesCompatState{model: "grok-test"}
got := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","item":{"type":"reasoning"}}`+"\n"), state)
if !bytes.Contains(got, []byte(`"id":"item_1"`)) {
t.Fatalf("item id not filled: %s", got)
}
got = rewriteResponsesDataLine([]byte(`data: {"type":"response.created","response":{"status":"in_progress"}}`+"\n"), state)
- if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) || !bytes.Contains(got, []byte(`"model":`)) {
+ if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) || !bytes.Contains(got, []byte(`"model":"grok-test"`)) {
t.Fatalf("response id/created_at/model not filled: %s", got)
}
}
@@ -1120,16 +1120,64 @@ func TestCopyStreamAbortTrailerAlwaysIncludesModel(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
- _, err := copyStream(context.Writer, &idleErrorReader{}, streamProtocolResponses, nil)
+ _, err := copyStreamWithFallbackModel(context.Writer, &idleErrorReader{}, streamProtocolResponses, nil, "grok-test")
if !errors.Is(err, errUpstreamStreamRead) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
- if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"model":`) {
+ if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"model":"grok-test"`) {
t.Fatalf("abort trailer missing model: %q", got)
}
}
+func TestCopyStreamAbortTrailerPrefersUpstreamModel(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ body := []byte(`data: {"type":"response.created","response":{"id":"resp_real","model":"upstream-model","status":"in_progress"}}` + "\n\n")
+ _, err := copyStreamWithFallbackModel(context.Writer, &chunkErrorReader{data: body}, streamProtocolResponses, nil, "request-model")
+ if !errors.Is(err, errUpstreamStreamRead) {
+ t.Fatalf("copy error = %v", err)
+ }
+ got := recorder.Body.String()
+ failedAt := strings.LastIndex(got, "event: response.failed")
+ if failedAt < 0 {
+ t.Fatalf("abort trailer missing: %q", got)
+ }
+ failed := got[failedAt:]
+ if !strings.Contains(failed, `"model":"upstream-model"`) || strings.Contains(failed, `"model":"request-model"`) {
+ t.Fatalf("abort trailer did not prefer upstream model: %q", failed)
+ }
+}
+
+func TestResponsesAbortTrailerUsesStandardErrorShape(t *testing.T) {
+ trailer := streamAbortTrailer(
+ streamProtocolResponses,
+ neterror.ErrUpstreamStreamIdleTimeout,
+ responseMetadata{},
+ &responsesCompatState{model: "grok-test"},
+ )
+ dataAt := bytes.Index(trailer, []byte("data: "))
+ if dataAt < 0 {
+ t.Fatalf("abort trailer missing data line: %q", trailer)
+ }
+ payload := bytes.TrimSpace(trailer[dataAt+len("data: "):])
+ var event struct {
+ Response struct {
+ Error map[string]any `json:"error"`
+ } `json:"response"`
+ }
+ if err := json.Unmarshal(payload, &event); err != nil {
+ t.Fatalf("decode abort trailer: %v; payload=%q", err, payload)
+ }
+ if event.Response.Error["code"] != "server_error" || !strings.Contains(stringAny(event.Response.Error["message"]), "upstream_stream_idle_timeout") {
+ t.Fatalf("unexpected Responses error: %#v", event.Response.Error)
+ }
+ if _, exists := event.Response.Error["type"]; exists {
+ t.Fatalf("Responses error contains non-protocol type: %#v", event.Response.Error)
+ }
+}
+
func TestSanitizeResponsesKeepsItemIDStableAcrossEvents(t *testing.T) {
state := &responsesCompatState{}
delta := rewriteResponsesDataLine([]byte(`data: {"type":"response.reasoning_text.delta","output_index":0,"delta":"plan"}`+"\n"), state)