fix(chat): retry the answer once when the provider drops the stream before any text; log each failed run's kind (BUG-2306)
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m49s
Independent Staging Quality Gate / validate-python (push) Successful in 7m25s
Independent Staging Quality Gate / publish (push) Successful in 3m14s

A follow-up showed only 「咨询暂时无法完成,本次不会扣点。」: the model provider closed the
stream (undici "terminated", other side closed) after the chart was computed and before any
answer text. The run now rewrites the answer once from the cached calculation; the dropped
stream's usage counts as unknown so settlement still succeeds; every failed run logs
[consult-run-failed] with kind, phase and last step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
This commit is contained in:
2026-11-24 10:54:51 +08:00
co-authored by Claude Opus 5.5
parent 4c1e5d7324
commit aaed85471f
5 changed files with 273 additions and 2 deletions
+22
View File
@@ -31000,3 +31000,25 @@
- 防复发:上面的测试;等待画面、回答卡片、收据地方都从路由 `requiredLayers` 取领域的宫(`domainChartHouses`)。
- 关联记录:BUG-2281(回答形状、地方和时间条语气)、BUG-2283(等待画面)、BUG-2048(一行状态)、BUG-1074(闲聊从事件读)、BUG-1539(推荐问题)。
- 修复版本:分支 `claude/chat-ui-fixes`(本地提交,待父会话推送 staging)。
## BUG-2306 | 点「接着问」的追问后只出现「咨询暂时无法完成,本次不会扣点。」,没有回答
- 状态:fixed-pending-verify(本地提交,未推送;待负责人在 staging 看过再推)。
- 首次发现 / 最近更新:2026-11-24(负责人在 staging 测 BUG-2281–2288 时截图)/ 2026-11-24。
- 现象:感情首轮回答之后点追问按钮「2027 年上半年我要不要在感情上更主动一点?」,等待行显示「分析了 4 步,用了 64 秒」,下面只有「咨询暂时无法完成,本次不会扣点。」,没有回答。同一对话再发同一句,84 秒后正常回答。
- 触发条件:模型供应商在写回答那一步把流断掉(undici `TypeError: terminated`,cause `SocketError: other side closed`),这时排盘已经完成、还没有一句回答发出去。和首轮、追问无关,和问题内容无关,偶发。
- 这句话从哪来:`frontend/src/lib/stream-agent-response.ts` `runFailedMessage` 的兜底(`calculation_failed`)。走到它的路:模型流里的 `error` 块(BUG-938,内部码 `provider_error` / `thinking_tool_choice_unsupported`)、回答写完之后结算或内容审核抛错(`onComplete` / `moderateOutput`)、其它没有分类的异常、回答还没出字就超时或中止。合同未完成、没写出回答、回答被截断或没过验收都是别的句子(「这次没能完成必要的计算……」「计算已完成,但这次没有生成回答……」「回答未完成……」)。429 排队重试用完是 `CONSULTATION_QUEUE_FAILED_MESSAGE` 那句。
- 证据:staging 管理端咨询记录(只读)里,负责人这次失败的请求 10:00:34 开始、10:01:36 变成 `cancelled`(61.5 秒,退点),重发的那次 10:04:43–10:06:05 完成;两次部署窗口是 09:23:31–09:24:46 和 09:35:28–09:36:42,之后没有部署,所以不是重启。重启断流时页面显示「连接中断,回答仍在后台生成,正在自动恢复。」,请求一直留在 `reserved` 直到 15 分钟租期,不会在 61 秒变成 `cancelled`。失败时页面上没有任何回答文字(失败前已经出字的话会留在页面上),说明断在出第一句之前;重发那次的分步耗时是第 0 步(排盘)48.8 秒、写回答 29.8 秒(前 23.5 秒在想),失败落在写回答的第 12 秒左右。staging 容器日志这边读不到(本机没有 staging 的 SSH 钥匙),所以线上那一次的内部码没有直接看到,用本地复现补上。
- 本地复现(origin/staging 60fc81b1b,真实 `POST /api/consult` 路由,公开盘 1961-08-04 Honolulu,本地引擎,默认模型 deepseek-flash,Supabase 用假的):感情首轮 + 同一句追问 4 次、事业首轮 + 第一个追问按钮 4 次,15 次模型回答里 1 次(事业首轮)失败,句子一模一样:排盘完成后写回答那一步 `validation:model-stream-error:failed`,内部码 `provider_error`,原文 `terminated` / `other side closed`,0 字,退点。在追问写回答的第一个请求上人为切断响应(同样的 `TypeError: terminated`),修复前追问 17 秒后同样出这句话。
- 排除:部署重启(时间和页面表现都不符);BUG-2287c `domains` 必填被退回(8 次追问都没有被退回的工具调用,退回也只是多一步,不会走到这句);BUG-2285c 保留结论句、验收、证据编号检查(失败码是 `answer_truncated`,句子不同);BUG-2286 只问一句走免费结算(追问回答都有结论,结算都是普通结算;结算失败要在回答出字之后);BUG-2284 不排盘声明(追问都排了盘);拆分删除后没有地方再读 `predictionSplit`。
- 根因:BUG-938 让咨询流认出供应商 `error` 块,但定的是「供应商错误直接失败」,没有区分已经算完盘、还没出字的这一种:用户一个字没看到,整轮作废,只能自己再发一次。另外失败只落在 stdout 的观测记录里,未分类的几种都记成 `calculation_failed`,事后分不出是哪一种。
- 修复:
- `stream-agent-response.ts`:第一轮模型循环因 `provider_error` 失败、排盘已完成、还没有任何回答文字发出时,用现有的 `retryForAnswer`(取回本次已缓存的计算,再写回答,受回答时钟管)重写一次;记一步 `validation provider-error-retry`;只重试一次,第二次再断照旧失败;已经出字的不重试(避免重复);排盘前断的不重试(BUG-938 的合同 retry 规则不变);`thinking_tool_choice_unsupported` 不重试。
- `consult/usage-list.ts`(新)+ `route.ts`:一次运行的用量列表在放进去时就接住拒绝,断掉的流的用量记为未知;否则重试后断流那一份用量的拒绝没人接(Node 直接退出进程),结算时 `Promise.all` 也会失败。
- 失败记录:每次失败打一行 `[consult-run-failed]`(requestId、公开码、内部类别 `provider_error` / `settlement_or_moderation_failed` / `timeout` / `aborted` / `unexpected_error` 等、阶段 tool / answer / settlement、是否已出字、模型步数、最后一步、错误名和原文头 160 字;不含用户或模型文字)。
- 仍在的保护:失败照旧不扣点;供应商拒收照旧不走合同 retry;回答已经出字后断流照旧按失败处理并保留已出的文字。
- 验证:新增 `frontend/tests/consult-run-failure-log-2306.test.ts` 6 条(写回答时断流记 provider_error / answer / 未出字;结算抛错记 settlement 阶段;完成的不记;断流后重写一次并完成、记 `provider-error-retry`;第二次断照旧失败、出字后断不重试;用量列表把拒绝变成未知用量),修复前因缺导出全部失败。相关测试逐个跑过:`consultation-agentic-runtime`(89)、`consult-answer-truncation-20260926`、`consult-single-pass-answer-20260927`、`consult-fact-guard-stream-1789`、`content-moderation`、`application-billing-contract`、`consultation-workflow-contract`、`consult-answer-clock-20261001`、`chat-blockers-2285-2288`、`consultation-stream-recovery`、`consult-reports-billing`、`consultation-workflow-retry`、`consult-evidence-card-telemetry-20260927`、`chat-answer-to-question-2284`、`consultation-context-cache-contract` 全过;`tsc` 0 错误,改动文件 eslint 0 错误。
- 本地真实链路(修复后):人为切断追问写回答的第一个请求,感情追问 2/2(46、46 秒)、事业追问 2/2(48、44 秒)照常回答(新样子,从「## 结论」开始)、普通结算扣 1 点,回执里有 `model-stream-error` 和 `provider-error-retry`;不切断的感情追问(37 秒)、事业追问(38 秒)照常完成。
- 为什么之前的测试没拦住:BUG-938 的测试只要求供应商错误「公开码 `calculation_failed`、不调合同 retry」,把整轮失败当成期望;BUG-2281–2288 的真实链路验证每条只跑一两次,这种 1/15 左右的上游断流碰不到。这不是 BUG-2281–2288 引入的:这条路从 BUG-938 起就是失败。
- 关联:BUG-938(供应商 `error` 块)、BUG-1051 / BUG-1053(截断与写回答步)、BUG-2281–2288(负责人测试时遇到)。
- 修复版本:分支 `claude/followup-failed`(本地)。
+3 -1
View File
@@ -24,6 +24,7 @@ import {
} from "@/lib/consult/prep-log";
import { reconcileConsultSessionModel } from "@/lib/consult/session-model-fallback";
import { loadConsultTurnHead } from "@/lib/consult/turn-prep";
import { createUsageList } from "@/lib/consult/usage-list";
import {
consultationCompletionSchema,
createConsultSettlement,
@@ -1236,7 +1237,8 @@ export async function POST(request: Request) {
loadResumableSessionId: async () => null,
};
const hooks = createConsultationRuntimeHooks(state);
const usages: Promise<Usage>[] = [];
// BUG-2306: a dropped stream's usage counts as unknown instead of rejecting the settlement after an answer retry.
const usages = createUsageList();
const agentStartedAt = Date.now();
let firstActivityMs = -1;
let firstTextMs = -1;
+13
View File
@@ -0,0 +1,13 @@
import type { Usage } from "./settlement.ts";
/**
* BUG-2306: the run's usage list. A model stream the provider dropped rejects its usage promise; once the run retries
* the answer instead of failing, that rejection had no handler (Node ends the process on an unhandled rejection) and
* made the later settlement fail. Every promise pushed here counts as unknown usage ({}) when it rejects.
*/
export function createUsageList(): Promise<Usage>[] {
const list: Promise<Usage>[] = [];
const push = list.push.bind(list);
list.push = (...items: Promise<Usage>[]) => push(...items.map((item) => Promise.resolve(item).catch(() => ({}) as Usage)));
return list;
}
+63 -1
View File
@@ -133,6 +133,8 @@ const SKILL_BINDING_FAILED = "skill_binding_failed";
const SKILL_BINDING_ABORT_STEP = "skill-binding-abort";
const RUNTIME_CONTRACT_INCOMPLETE_STEP = "runtime-contract-incomplete";
const CONTRACT_DEGRADED_STEP = "contract-degraded";
/** BUG-2306: the one answer retry after the provider dropped the stream before any answer text. */
export const PROVIDER_ERROR_RETRY_STEP = "provider-error-retry";
/** Server-owned; never generated by the model. Voice: 直接,不说法务腔. */
export const CONTRACT_DEGRADED_NOTE = "\n\n这次没跑完星盘计算,上面是模型直接写的,先看着。";
@@ -169,6 +171,23 @@ function runFailedCode(error: unknown, emitted: boolean): RunFailedCode {
return "calculation_failed";
}
const INTERNAL_FAILURE_KINDS = new Set([
"runtime_contract_incomplete",
SKILL_BINDING_FAILED,
"empty_answer",
"answer_truncated",
"thinking_tool_choice_unsupported",
"provider_error",
]);
/** BUG-2306: the failure behind a run.failed code, finer than the code (several kinds share one user sentence). */
export function runFailureKind(error: unknown, failedWhileSettling: boolean): string {
if (error instanceof Error && INTERNAL_FAILURE_KINDS.has(error.message)) return error.message;
if (isTimeoutOrAbort(error)) return (error as Error).name === "TimeoutError" ? "timeout" : "aborted";
if (failedWhileSettling) return "settlement_or_moderation_failed";
return "unexpected_error";
}
function runFailedMessage(code: RunFailedCode) {
if (code === "runtime_contract_incomplete") return "这次没能完成必要的计算,没有扣点。请再问一次。";
if (code === "empty_answer") return "计算已完成,但这次没有生成回答,本次不会扣点。请再发送一次。";
@@ -1464,6 +1483,34 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
}
}
/**
* BUG-2306: one line per failed run saying which failure is behind the sentence the user saw. Every unclassified
* failure (model stream error, settlement error, any other throw) shows the same 「咨询暂时无法完成,本次不会扣点。」,
* and the observability record folds them into `calculation_failed`. No user or model text: the run's codes, the
* phase it failed in, the last recorded step and the head of the error message.
*/
function logRunFailure(error: unknown, failedWhileSettling: boolean) {
try {
const code = runFailedCode(error, emitted);
const message = error instanceof Error ? error.message : String(error);
const lastStep = options.state.steps[options.state.steps.length - 1];
console.error("[consult-run-failed]", {
requestId: options.requestId,
code,
kind: runFailureKind(error, failedWhileSettling),
phase: failedWhileSettling ? "settlement" : answerPhaseStarted || contractReady(options) ? "answer" : "tool",
emitted,
modelSteps: options.state.modelStepCount,
toolSuccesses: options.state.consultationToolSuccessCount,
...(lastStep ? { lastStep: `${lastStep.kind}:${lastStep.name}:${lastStep.status}${lastStep.failureCode ? `:${lastStep.failureCode}` : ""}`.slice(0, 160) } : {}),
errorName: error instanceof Error ? error.name : typeof error,
messageHead: message.slice(0, 160),
});
} catch {
// Logging never changes how a run fails.
}
}
function recordAnswerTelemetry() {
const writer = answerTail ?? lastAttempt;
if (writer) {
@@ -1491,7 +1538,20 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
await options.warmup((event) => send(controller, event));
flushThinkingPlan(controller);
}
await consumeAttempt(controller, await resolveAgentStream(options.stream));
try {
await consumeAttempt(controller, await resolveAgentStream(options.stream));
} catch (error) {
// BUG-2306: the provider dropped the model stream ("terminated", other side closed) after the calculation
// was in hand and before any answer text went out. One fresh answer attempt against the cached
// calculation, instead of failing a paid question on a transient connection drop.
if (!(error instanceof Error && error.message === "provider_error")
|| emitted || !contractReady(options) || !options.retryForAnswer) throw error;
appendConsultationRuntimeStep(options.state, { kind: "validation", name: PROVIDER_ERROR_RETRY_STEP, status: "completed" });
send(controller, { type: "activity", phase: "answer-composition", label: "正在组织回答" });
pass4Buffer = "";
fullOutput = "";
await consumeAttempt(controller, await options.retryForAnswer(), { answerPhase: true });
}
if (!contractReady(options) && options.retry && !replyWithoutChart(options.state)) {
appendConsultationRuntimeStep(options.state, { kind: "validation", name: "runtime-contract-retry", status: "completed" });
send(controller, { type: "activity", phase: "loading-method", label: "正在补齐方法与计算步骤" });
@@ -1621,9 +1681,11 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
if (!disconnected) controller.close();
} catch (error) {
if (settled) return;
const failedWhileSettling = settling;
settled = true;
settling = false;
recordAnswerTelemetry();
logRunFailure(error, failedWhileSettling);
try {
await options.onError?.(error, emitted, fullOutput);
} catch {}
@@ -0,0 +1,172 @@
// BUG-2306: a follow-up ended with 「咨询暂时无法完成,本次不会扣点。」 on staging and nothing recorded which failure
// it was. That sentence is the run.failed `calculation_failed` message, shared by a model stream error, a settlement
// error and any other throw; the observability record folds the unclassified ones into `calculation_failed` too.
// Each failed run now logs one `[consult-run-failed]` line with the failure kind, the phase and the last step.
import assert from "node:assert/strict";
import test from "node:test";
import { natalConsultationThinkingPlan } from "../src/lib/consultation-thinking-plan.ts";
import { PROVIDER_ERROR_RETRY_STEP, runFailureKind, streamAgentResponse } from "../src/lib/stream-agent-response.ts";
import {
consultationStepBudgetReceipt,
createConsultationRuntimeState,
publicConsultationRuntimeSteps,
} from "../src/mastra/consultation-tools.ts";
type RuntimeState = ReturnType<typeof createConsultationRuntimeState>;
function toolReadyState() {
const state = createConsultationRuntimeState();
state.jyotishSkillBound = true;
state.consultationToolCallCount = 1;
state.consultationToolSuccessCount = 1;
state.consultationToolCompleted = true;
state.workflowReceipt = { route: "marriage", status: "ready", preciseTiming: "blocked", missingLayers: [] };
state.thinkingPlan = natalConsultationThinkingPlan({ domains: ["marriage"] });
return state;
}
function receipt(state: RuntimeState) {
return {
runId: "run",
runtime: "mastra-agentic" as const,
skill: { name: "jyotish-vedic-astrology" as const, loaded: true, referenceReads: 0, methodologySections: 0 },
steps: publicConsultationRuntimeSteps(state),
stepBudget: consultationStepBudgetReceipt(state),
workflow: state.workflowReceipt!,
techniqueTruth: "unknown",
};
}
async function* chunks(parts: readonly unknown[]) {
for (const part of parts) yield part;
}
async function runAndCapture(
state: RuntimeState,
parts: readonly unknown[],
onComplete?: () => Promise<void>,
retryForAnswer?: () => Promise<AsyncIterable<unknown>>,
) {
const logged: unknown[][] = [];
const original = console.error;
console.error = (...args: unknown[]) => { logged.push(args); };
try {
const response = streamAgentResponse({
runId: "run",
requestId: "req-2306",
state,
requireTool: true,
stream: chunks(parts),
toolStatus: () => "ready",
receipt: () => receipt(state),
onComplete,
...(retryForAnswer ? { retryForAnswer } : {}),
});
const events = (await response.text()).split("\n").filter(Boolean).map((line) => JSON.parse(line) as Record<string, unknown>);
const failure = logged.find((args) => args[0] === "[consult-run-failed]")?.[1] as Record<string, unknown> | undefined;
return { events, failure };
} finally {
console.error = original;
}
}
const DROPPED = [
{ type: "step-start" },
{ type: "reasoning-delta", payload: { text: "先看" } },
{ type: "error", payload: { error: new TypeError("terminated") } },
];
const FINISHED_ANSWER = [
{ type: "step-start" },
{ type: "text-delta", payload: { text: "要主动一点,2027 年 2 月到 5 月最好。\n" } },
{ type: "step-finish", payload: { stepResult: { reason: "stop" } } },
{ type: "finish", payload: { stepResult: { reason: "stop" }, output: { steps: [{}] } } },
];
test("BUG-2306: a model stream error while the answer is being written is logged as provider_error in the answer phase", async () => {
const { events, failure } = await runAndCapture(toolReadyState(), [
{ type: "step-start" },
{ type: "error", payload: { error: new Error("Service Unavailable") } },
]);
const failed = events.find((event) => event.type === "run.failed");
assert.equal(failed?.code, "calculation_failed");
assert.equal(failed?.message, "咨询暂时无法完成,本次不会扣点。");
assert.ok(failure, "the failed run leaves a [consult-run-failed] line");
assert.equal(failure.requestId, "req-2306");
assert.equal(failure.code, "calculation_failed");
assert.equal(failure.kind, "provider_error");
assert.equal(failure.phase, "answer");
assert.equal(failure.emitted, false);
assert.match(String(failure.lastStep), /model-stream-error/u);
});
test("BUG-2306: a settlement error after a finished answer is logged in the settlement phase, not as a calculation", async () => {
const { events, failure } = await runAndCapture(toolReadyState(), FINISHED_ANSWER, async () => {
throw new Error("completion_rejected");
});
const failed = events.find((event) => event.type === "run.failed");
assert.equal(failed?.message, "咨询暂时无法完成,本次不会扣点。");
assert.ok(failure);
assert.equal(failure.kind, "settlement_or_moderation_failed");
assert.equal(failure.phase, "settlement");
assert.equal(failure.emitted, true);
assert.equal(failure.messageHead, "completion_rejected");
});
test("BUG-2306: a completed run logs no failure line, and the kinds keep the internal codes", async () => {
const { events, failure } = await runAndCapture(toolReadyState(), FINISHED_ANSWER, async () => {});
assert.ok(events.some((event) => event.type === "run.completed"));
assert.equal(failure, undefined);
assert.equal(runFailureKind(new Error("runtime_contract_incomplete"), false), "runtime_contract_incomplete");
assert.equal(runFailureKind(new Error("something else"), false), "unexpected_error");
});
test("BUG-2306: a stream the provider dropped before any answer text gets one fresh answer attempt and completes", async () => {
const state = toolReadyState();
let retries = 0;
const { events, failure } = await runAndCapture(state, DROPPED, async () => {}, async () => {
retries += 1;
return chunks(FINISHED_ANSWER);
});
assert.equal(retries, 1);
assert.equal(events.some((event) => event.type === "run.failed"), false);
assert.ok(events.some((event) => event.type === "run.completed"));
const text = events.filter((event) => event.type === "answer.delta").map((event) => String(event.text)).join("");
assert.match(text, /要主动一点/u);
assert.ok(state.steps.some((step) => step.name === PROVIDER_ERROR_RETRY_STEP));
assert.equal(failure, undefined);
});
test("BUG-2306: a second drop fails as before (one retry only), and a drop after answer text is not retried", async () => {
let retries = 0;
const twice = await runAndCapture(toolReadyState(), DROPPED, async () => {}, async () => {
retries += 1;
return chunks(DROPPED);
});
assert.equal(retries, 1);
assert.equal(twice.events.find((event) => event.type === "run.failed")?.message, "咨询暂时无法完成,本次不会扣点。");
assert.equal(twice.failure?.kind, "provider_error");
let lateRetries = 0;
const late = await runAndCapture(toolReadyState(), [
{ type: "step-start" },
{ type: "text-delta", payload: { text: "要主动一点,2027 年 2 月到 5 月最好。\n" } },
{ type: "error", payload: { error: new TypeError("terminated") } },
], async () => {}, async () => {
lateRetries += 1;
return chunks(FINISHED_ANSWER);
});
assert.equal(lateRetries, 0);
assert.ok(late.events.some((event) => event.type === "run.failed"));
assert.equal(late.failure?.emitted, true);
});
test("BUG-2306: the run's usage list turns a dropped stream's rejected usage into unknown usage", async () => {
const { createUsageList } = await import("../src/lib/consult/usage-list.ts");
const usages = createUsageList();
usages.push(Promise.reject(new TypeError("terminated")));
usages.push(Promise.resolve({ inputTokens: 10, outputTokens: 2 }));
const resolved = await Promise.all(usages);
assert.deepEqual(resolved, [{}, { inputTokens: 10, outputTokens: 2 }]);
});