fix(consult): the plan starter no longer fails on a skipped classification, and any throw after the reservation releases it (BUG-2166)
The bare plan-timing starter (BUG-2161) skips classification, so classifyStarted stayed 0 and prep.classify logged Date.now() ms; the observability schema caps durations at 7 days, logPrep() threw, and the turn failed after the credit / first-free reservation with nothing cancelling it. The request stayed reserved, held first_consult_free_request_id, and the next question answered 402. - skipped classification logs skipped, 0 ms - logPrep drops a rejected event with a log line instead of throwing - the reservation registers a release hook; stream-first onUnhandled and the legacy runTurn catch both cancel it (a no-op for completed requests) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
@@ -29259,3 +29259,17 @@
|
||||
- 尚未处理:问答卡侧待核状态(卡上目前只把引擎标签换成已核说法,`variant_only` 的星仍按「落陷」写,不说有缓解);旧问答回答里的长句不改写。
|
||||
- 关联记录:BUG-2154、BUG-2155、BUG-2156、BUG-2157、BUG-2151、BUG-2152、BUG-2030、BUG-2148。
|
||||
- 修复版本:`claude/defg-consumers-2163`。
|
||||
|
||||
## BUG-2166 | 新账户点首页「今年推进重要计划」:回复「咨询服务暂时不可用」,预留一直卡住,下一问要求兑换点数
|
||||
|
||||
- 状态:fixed-pending-verify。
|
||||
- 首次发现 / 最近更新:2026-11-22 / 2026-11-22。
|
||||
- 现象:测试环境(bbdb2749)新账户(首问免费未用、余额 0)点首页第三问,请求带 `entrypoint: "starter_plan_timing"`,流里先收到「收到」,随后 `run.failed`(`calculation_failed`,「咨询服务暂时不可用,请稍后再试。」)。这条请求一直停在 `reserved`,占着首问免费(`first_consult_free_request_id`),`first_consult_free_used_at` 仍为空;再问任何问题都返回 402「请先兑换咨询点数后再继续。」——新用户第一次提问就被锁住。
|
||||
- 触发条件:首页计划问题原样发出(BUG-2161 的免费追问分支);以及任何在预留之后、交回响应之前抛错的情况。
|
||||
- 根因:(1) BUG-2161 让原样发出的计划问题跳过分类,`classifyStarted` 停在 0,`prep.classify` 阶段记的耗时是 `Date.now() - 0`(约 1.7×10¹² 毫秒),超过观测记录 7 天的上限;`logPrep()` 里 `logAgentObservability` 用 schema 严格校验,直接抛 ZodError(`frontend/src/app/api/consult/route.ts` 分类阶段记录处与 `logPrep`)。(2) 抛错发生在预留之后、交回响应之前;流式外壳的 `onUnhandled` 只写日志、不取消预留(BUG-1074 把整轮搬进 `runTurn` 时留下),旧运行时的 `runTurn()` 也没有兜底,所以请求永远停在 `reserved`。没有过期释放的任务。
|
||||
- 修复:(1) 没有启动分类时,两个分类阶段记 `skipped`、0 毫秒。(2) `logPrep` 包一层 try:观测记录被拒只写一行日志,不让用户这一轮失败。(3) 预留成功后登记释放函数 `releaseOnThrow`;流式外壳的 `onUnhandled` 和旧运行时的兜底 catch 都调用 `releaseAfterThrow`,取消这条预留(`cancel_consultation_credit` 对已完成的请求是空操作,不会把已扣的点数退回),从而也释放首问免费。追问本身走 `complete_consultation_free`,本来就会释放首问免费的占用,修复后追问不再消耗首问免费。
|
||||
- 验证:新增 `frontend/tests/plan-clarify-reserve-2166.test.ts`(5 项):测试环境那条事件确实被 schema 拒绝、跳过形式被接受;跳过分类记 skipped;`logPrep` 不再抛;预留之后两种运行时的抛错都会释放;流式外壳抛错时先调释放再发失败帧。取消释放首问免费由 `database-onboarding-journey.test.ts` 覆盖。`agent-observability.test.ts`、`consult-first-frame-and-pacing-20260928.test.tsx` 各一处源码断言按原值 / 新值 / 原因更新。
|
||||
- 防复发:上述测试;以后新增跳过某个准备阶段的分支时,阶段耗时不能用未启动的起点算。
|
||||
- 尚未处理:测试环境那个新测试账户的请求仍停在 `reserved`,需要用服务端角色执行一次取消(见交付说明),本修复不会自动处理已卡住的旧请求。另:新账户引导里选海外出生地点提交报「账户资料格式不正确」(出生地点来源 `world_location_table` 不在资料更新允许的来源里),另行处理。
|
||||
- 关联记录:BUG-2161、BUG-2160、BUG-1074、BUG-1431。
|
||||
- 修复版本:`claude/plan-clarify-reserve-2166`。
|
||||
|
||||
@@ -540,11 +540,18 @@ export async function POST(request: Request) {
|
||||
function logPrep() {
|
||||
if (prepLogged) return;
|
||||
prepLogged = true;
|
||||
logAgentObservability(consultPrepObservabilityEvent({
|
||||
requestId,
|
||||
sessionId,
|
||||
phases: prepPhases,
|
||||
}));
|
||||
// BUG-2166: diagnostics only. An event the observability schema rejects is
|
||||
// dropped with a log line instead of failing the user's turn.
|
||||
try {
|
||||
logAgentObservability(consultPrepObservabilityEvent({
|
||||
requestId,
|
||||
sessionId,
|
||||
phases: prepPhases,
|
||||
}));
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : "UnknownError";
|
||||
console.error(`[consult] prep log rejected request=${requestId} reason=${reason}`);
|
||||
}
|
||||
}
|
||||
async function settleInputModeration(): Promise<ModerationResult | null> {
|
||||
if (!inputModerationPending) return null;
|
||||
@@ -596,6 +603,11 @@ export async function POST(request: Request) {
|
||||
// always did, and `streamFirstResponse` relays them after a first frame that
|
||||
// goes out before any of this work starts. The legacy runtime keeps the
|
||||
// pre-stream order because its text/plain replies cannot ride an NDJSON stream.
|
||||
// BUG-2166: once a credit (or the first free question) is reserved, a throw
|
||||
// before runTurn hands back a Response would leave the request "reserved" and
|
||||
// hold the user's credit / first free question with no way out (the next
|
||||
// question answers 402). Whoever catches that throw releases it through here.
|
||||
const releaseOnThrow: { current: (() => Promise<unknown>) | null } = { current: null };
|
||||
const runTurn = async (): Promise<Response> => {
|
||||
const modelSlot: { current: SelectedModel | null } = { current: null };
|
||||
let classificationUsage: SmalltalkUsage = {};
|
||||
@@ -885,6 +897,9 @@ export async function POST(request: Request) {
|
||||
async function cancel(): Promise<AgentSettlementResult> {
|
||||
return consultSettlement.cancel();
|
||||
}
|
||||
// cancel_consultation_credit is a no-op for a completed request, so releasing
|
||||
// after a later throw never refunds a reading that was already charged.
|
||||
releaseOnThrow.current = cancel;
|
||||
|
||||
const storedHistory = historyWindow.tail;
|
||||
const birthFields = consultationBirthFields(currentBirth);
|
||||
@@ -903,15 +918,19 @@ export async function POST(request: Request) {
|
||||
// Started in beforeReserve, beside reserve + append (issue #162).
|
||||
const classifyWaitStarted = Date.now();
|
||||
const turn = earlyClassification.turn ? await earlyClassification.turn : { kind: "consult" as const };
|
||||
// BUG-2166 原值:两个分类阶段总写成 completed,耗时 = now - classifyStarted;新值:没有启动分类
|
||||
// (首页计划问题原样发出、其他产品入口)就记 skipped、0 毫秒;原因:classifyStarted 停在 0 时耗时是整个
|
||||
// 纪元毫秒数,超过观测记录的 7 天上限,logPrep() 抛错,整轮失败且预留的点数 / 首问免费不释放。
|
||||
const classificationRan = earlyClassification.turn !== null;
|
||||
prepPhases.push({
|
||||
phase: "prep.classify_wait",
|
||||
durationMs: Math.max(0, Date.now() - classifyWaitStarted),
|
||||
status: "completed",
|
||||
durationMs: classificationRan ? Math.max(0, Date.now() - classifyWaitStarted) : 0,
|
||||
status: classificationRan ? "completed" : "skipped",
|
||||
});
|
||||
prepPhases.push({
|
||||
phase: "prep.classify",
|
||||
durationMs: classificationDurationMs ?? Math.max(0, Date.now() - classifyStarted),
|
||||
status: "completed",
|
||||
durationMs: classificationRan ? classificationDurationMs ?? Math.max(0, Date.now() - classifyStarted) : 0,
|
||||
status: classificationRan ? "completed" : "skipped",
|
||||
});
|
||||
|
||||
// BUG-2161 (astrologer 2026-11-22 J §9): the plan-timing starter sent bare
|
||||
@@ -2136,7 +2155,25 @@ export async function POST(request: Request) {
|
||||
}
|
||||
};
|
||||
|
||||
if (!shouldUseAgenticRuntime(user)) return runTurn();
|
||||
async function releaseAfterThrow(error: unknown) {
|
||||
const reason = error instanceof Error ? error.name : "UnknownError";
|
||||
console.error(`[consult] turn failed before a response request=${requestId} reason=${reason}`);
|
||||
const release = releaseOnThrow.current;
|
||||
releaseOnThrow.current = null;
|
||||
if (release) await release().catch(() => {});
|
||||
}
|
||||
|
||||
if (!shouldUseAgenticRuntime(user)) {
|
||||
try {
|
||||
return await runTurn();
|
||||
} catch (error) {
|
||||
await releaseAfterThrow(error);
|
||||
return NextResponse.json(
|
||||
{ error: "暂时无法生成解读", message: "咨询服务暂时不可用,请稍后再试。" },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
}
|
||||
return streamFirstResponse({
|
||||
requestId,
|
||||
run: runTurn,
|
||||
@@ -2150,9 +2187,6 @@ export async function POST(request: Request) {
|
||||
billingSettlementResult: "not_applicable",
|
||||
});
|
||||
},
|
||||
onUnhandled: (error) => {
|
||||
const reason = error instanceof Error ? error.name : "UnknownError";
|
||||
console.error(`[consult] turn failed before a response request=${requestId} reason=${reason}`);
|
||||
},
|
||||
onUnhandled: releaseAfterThrow,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -255,6 +255,8 @@ test("an agentic run that fails before streaming still emits the observability e
|
||||
// reach the same entry point instead of a bare cancel().
|
||||
assert.match(route, /agenticFailure\.report = async \(error\) => \{/);
|
||||
assert.match(route, /settleRun\(cancel, toAgentObservabilityErrorCode\(error\)\)/);
|
||||
const requestCatch = route.slice(route.lastIndexOf("} catch (error) {"));
|
||||
// BUG-2166 原值:取最后一个 `} catch (error) {`;新值:取生成阶段那一个(在 releaseAfterThrow 之前);
|
||||
// 原因:路由末尾新增了旧运行时的 runTurn 兜底 catch,它成了文件里最后一个 catch。
|
||||
const requestCatch = route.slice(route.lastIndexOf("} catch (error) {", route.indexOf("async function releaseAfterThrow")));
|
||||
assert.match(requestCatch, /if \(agenticFailure\.report\) await agenticFailure\.report\(error\);\s*\n\s*else await cancel\(\);/);
|
||||
});
|
||||
|
||||
@@ -295,7 +295,9 @@ test("the consult route opens the stream before subject reads, reservation, ques
|
||||
assert.match(settlement, /rpc\("reserve_consultation_usage"/);
|
||||
assert.match(settlement, /rpc\("append_consultation_question"/);
|
||||
assert.match(settlement, /code: "session_full"/);
|
||||
assert.match(route, /if \(!shouldUseAgenticRuntime\(user\)\) return runTurn\(\);/);
|
||||
// BUG-2166 原值:`if (!shouldUseAgenticRuntime(user)) return runTurn();`;新值:旧运行时同样直接跑 runTurn,
|
||||
// 但包一层 try,抛错时先释放已预留的点数 / 首问免费;原因:抛错曾让预留一直停在 reserved。
|
||||
assert.match(route, /if \(!shouldUseAgenticRuntime\(user\)\) \{\s*try \{\s*return await runTurn\(\);/);
|
||||
assert.match(route, /return streamFirstResponse\(\{\s*requestId,\s*run: runTurn,\s*startedAt: requestStartedAt,/);
|
||||
assert.match(route, /phase: "first_byte", durationMs: elapsedMs, status: "completed"/);
|
||||
// The smalltalk branch is untouched: it still settles for free and never runs the agent.
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { agentObservabilityEventSchema } from "../src/lib/agent-observability.ts";
|
||||
import { consultPrepObservabilityEvent } from "../src/lib/consult/prep-log.ts";
|
||||
import { streamFirstResponse } from "../src/lib/stream-first-response.ts";
|
||||
|
||||
// BUG-2166: the plan-timing starter (BUG-2161) skips classification, so
|
||||
// classifyStarted stayed 0 and prep.classify logged ~1.7e12 ms. The
|
||||
// observability schema caps durations at 7 days, logPrep() threw, the turn
|
||||
// failed with 「咨询服务暂时不可用」, and nothing cancelled the reservation:
|
||||
// the request stayed "reserved", held the first free question, and the next
|
||||
// question answered 402.
|
||||
const route = readFileSync(new URL("../src/app/api/consult/route.ts", import.meta.url), "utf8");
|
||||
const requestId = "99999999-9999-4999-8999-999999992166";
|
||||
const sessionId = "99999999-9999-4999-8999-999999992167";
|
||||
|
||||
test("the staging event that broke the turn is rejected; the skipped form is accepted", () => {
|
||||
const epochDuration = Date.now() - 0;
|
||||
const broken = consultPrepObservabilityEvent({ requestId, sessionId, phases: [
|
||||
{ phase: "prep.classify", durationMs: epochDuration, status: "completed" },
|
||||
] });
|
||||
assert.equal(agentObservabilityEventSchema.safeParse(broken).success, false);
|
||||
const skipped = consultPrepObservabilityEvent({ requestId, sessionId, phases: [
|
||||
{ phase: "prep.classify_wait", durationMs: 0, status: "skipped" },
|
||||
{ phase: "prep.classify", durationMs: 0, status: "skipped" },
|
||||
] });
|
||||
assert.equal(agentObservabilityEventSchema.safeParse(skipped).success, true);
|
||||
});
|
||||
|
||||
test("a turn that never classified logs skipped classification with zero duration", () => {
|
||||
assert.match(route, /const classificationRan = earlyClassification\.turn !== null;/);
|
||||
assert.match(route, /durationMs: classificationRan \? classificationDurationMs \?\? Math\.max\(0, Date\.now\(\) - classifyStarted\) : 0,/);
|
||||
assert.match(route, /status: classificationRan \? "completed" : "skipped",/);
|
||||
});
|
||||
|
||||
test("prep logging can no longer fail the user's turn", () => {
|
||||
const body = route.slice(route.indexOf("function logPrep()"), route.indexOf("async function settleInputModeration"));
|
||||
assert.match(body, /try \{\s*logAgentObservability\(consultPrepObservabilityEvent/);
|
||||
assert.match(body, /catch \(error\)/);
|
||||
});
|
||||
|
||||
test("any throw after the reservation releases it, on both runtimes", () => {
|
||||
const reservedAt = route.indexOf("releaseOnThrow.current = cancel;");
|
||||
assert.ok(reservedAt > route.indexOf('const insufficient = reserveResult.error_code === "insufficient_credits"'),
|
||||
"registered only after a successful reservation");
|
||||
assert.ok(reservedAt < route.indexOf("const appended = await consultSettlement.appendQuestion();"),
|
||||
"registered before anything else can throw");
|
||||
assert.match(route, /onUnhandled: releaseAfterThrow,/);
|
||||
assert.match(route, /if \(!shouldUseAgenticRuntime\(user\)\) \{\s*try \{\s*return await runTurn\(\);\s*\} catch \(error\) \{\s*await releaseAfterThrow\(error\);/);
|
||||
const release = route.slice(route.indexOf("async function releaseAfterThrow"), route.indexOf("if (!shouldUseAgenticRuntime(user))"));
|
||||
assert.match(release, /releaseOnThrow\.current = null;/, "released at most once");
|
||||
assert.match(release, /await release\(\)\.catch\(\(\) => \{\}\);/);
|
||||
});
|
||||
|
||||
test("stream-first hands the throw to the release hook before ending with a failure frame", async () => {
|
||||
const released: string[] = [];
|
||||
const response = streamFirstResponse({
|
||||
requestId,
|
||||
run: async () => { throw new Error("prep log rejected"); },
|
||||
onUnhandled: async () => { released.push("cancel"); },
|
||||
});
|
||||
const text = await response.text();
|
||||
assert.deepEqual(released, ["cancel"]);
|
||||
assert.match(text, /"type":"run\.failed"/);
|
||||
// The release itself (cancel_consultation_credit clears first_consult_free_request_id so the
|
||||
// next question can use the first free question) is covered by database-onboarding-journey.test.ts.
|
||||
});
|
||||
Reference in New Issue
Block a user