Files
Jyotisha/frontend/tests/model-fallback-2347.test.ts
ClaudeandClaude Opus 5.5 049614ffa0
Independent Staging Quality Gate / validate-python (push) Successful in 6m38s
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m48s
Independent Staging Quality Gate / publish (push) Successful in 7m54s
fix(model): the admin's fallback model answers when the default provider fails (BUG-2347, #352)
- A provider-side failure (401/403/408/409/429/5xx, timeout, network) before any
  answer content reached the user moves the call once to the published fallback
  model; a stream is never switched after content has streamed.
- Settlement prices the tokens with the model that answered (per-request /
  per-job scope); credits charged are unchanged.
- 功能开关「暂停聊天」 (ops.chat_paused): an emergency stop, answered before any
  credit is reserved; a failed read keeps chat open.
- Daily model spend alert from usage_ledger (MODEL_DAILY_SPEND_ALERT_USD, default
  $30), throttled, forwarded by the monitor on first occurrence; per-user spend
  view on /admin/usage.

Checks: tsc clean; eslint 0 errors; new tests model-fallback-2347 (11) and
model-spend-alert-2347 (5) pass; digest Python tests pass; Python quick gate
passed; full frontend suite 5334 tests, 28 failures, all the known
environment set (PostgreSQL, compose, YAML, staging sync, swisseph).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-25 10:58:47 +08:00

193 lines
9.8 KiB
TypeScript

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { KNOWN_FEATURE_FLAGS, flagEffect } from "../src/lib/admin/known-feature-flags.ts";
import { ProviderKeyPool } from "../src/lib/model-key-pool.ts";
import { servedModel, servedUsageModel, withModelServeScope } from "../src/lib/model-serve-scope.ts";
import {
PooledProviderLanguageModel,
providerFailureAllowsFallback,
type FallbackTarget,
} from "../src/lib/pooled-language-model.ts";
// BUG-2347: the admin's fallback model answers when the default model's provider fails before
// anything reached the user; usage is then priced as the fallback; a stream is never switched
// once answer content has arrived.
type Options = Parameters<PooledProviderLanguageModel["doStream"]>[0];
type Result = Awaited<ReturnType<PooledProviderLanguageModel["doStream"]>>;
const options = (abortSignal?: AbortSignal) => ({ prompt: [], abortSignal }) as unknown as Options;
const apiError = (statusCode: number) => Object.assign(new Error(`provider answered ${statusCode}`), { statusCode });
const primaryModel = { id: "deepseek-pro", configVersion: 3, inputCostMicrousdPerMillion: 270_000, outputCostMicrousdPerMillion: 1_100_000 };
const fallbackServed = { id: "claude-backup", configVersion: 7, inputCostMicrousdPerMillion: 3_000_000, outputCostMicrousdPerMillion: 15_000_000 };
function streamOf(parts: unknown[], error?: unknown) {
return new ReadableStream<unknown>({
start(controller) {
for (const part of parts) controller.enqueue(part);
if (error !== undefined) controller.error(error);
else controller.close();
},
});
}
async function readAll(stream: ReadableStream<unknown>) {
const parts: unknown[] = [];
const reader = stream.getReader();
for (;;) { const next = await reader.read(); if (next.done) return parts; parts.push(next.value); }
}
type Handler = (method: "doGenerate" | "doStream") => Promise<Result>;
function pooled(modelId: string, handler: Handler, fallback?: () => Promise<FallbackTarget | null>) {
const pool = new ProviderKeyPool();
pool.configure([{ id: `${modelId}-k1`, label: "k1", maxConcurrency: null }]);
let calls = 0;
const model = new PooledProviderLanguageModel(
{ providerId: modelId.split("-")[0]!, modelId, url: "https://api.example.test/v1" },
pool,
[{ id: `${modelId}-k1`, apiKey: "secret" }],
{
modelId,
fallback,
createInner: () => ({
doGenerate: () => { calls += 1; return handler("doGenerate"); },
doStream: () => { calls += 1; return handler("doStream"); },
}),
},
);
return { model, calls: () => calls };
}
function withFallback(primary: Handler) {
const backup = pooled("claude-backup", async () => ({ stream: streamOf([{ type: "text-delta", delta: "备用模型的回答" }]) }) as unknown as Result);
const main = pooled("deepseek-pro", primary, async () => ({ model: backup.model, served: fallbackServed }));
return { main, backup };
}
test("a 503 before the stream: the fallback answers and usage is priced as the fallback", async () => {
const { main, backup } = withFallback(async () => { throw apiError(503); });
await withModelServeScope(async () => {
const result = await main.model.doStream(options());
assert.deepEqual(await readAll(result.stream as ReadableStream<unknown>), [{ type: "text-delta", delta: "备用模型的回答" }]);
assert.equal(backup.calls(), 1);
assert.deepEqual(servedModel(primaryModel), fallbackServed);
assert.deepEqual(servedUsageModel(primaryModel), { actualModelId: "claude-backup", modelConfigVersion: 7 });
});
});
test("a 429 on the only key moves to the fallback; doGenerate too", async () => {
const { main, backup } = withFallback(async () => { throw apiError(429); });
await withModelServeScope(async () => {
await main.model.doGenerate(options());
assert.equal(backup.calls(), 1);
assert.equal(servedModel(primaryModel).id, "claude-backup");
});
});
test("a network failure moves to the fallback; a bad request (400) does not", async () => {
const network = withFallback(async () => { throw Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNRESET" } }); });
await network.main.model.doStream(options());
assert.equal(network.backup.calls(), 1);
const bad = withFallback(async () => { throw apiError(400); });
await assert.rejects(bad.main.model.doStream(options()), /provider answered 400/);
assert.equal(bad.backup.calls(), 0);
});
test("a cancelled request is never moved to the fallback", async () => {
const controller = new AbortController();
controller.abort();
const { main, backup } = withFallback(async () => { throw apiError(503); });
await assert.rejects(main.model.doStream(options(controller.signal)));
assert.equal(backup.calls(), 0);
assert.equal(providerFailureAllowsFallback(apiError(503), controller.signal), false);
});
test("an error part before any content still moves to the fallback", async () => {
const { main, backup } = withFallback(async () => ({
stream: streamOf([{ type: "stream-start", warnings: [] }, { type: "error", error: apiError(502) }]),
}) as unknown as Result);
await withModelServeScope(async () => {
const result = await main.model.doStream(options());
assert.deepEqual(await readAll(result.stream as ReadableStream<unknown>), [{ type: "text-delta", delta: "备用模型的回答" }]);
assert.equal(backup.calls(), 1);
assert.equal(servedModel(primaryModel).id, "claude-backup");
});
});
test("once answer content has streamed, a later failure is never switched", async () => {
const parts = [{ type: "stream-start", warnings: [] }, { type: "text-delta", delta: "已经开始的回答" }, { type: "error", error: apiError(500) }];
const { main, backup } = withFallback(async () => ({ stream: streamOf(parts) }) as unknown as Result);
await withModelServeScope(async () => {
const result = await main.model.doStream(options());
assert.deepEqual(await readAll(result.stream as ReadableStream<unknown>), parts);
assert.equal(backup.calls(), 0);
assert.equal(servedModel(primaryModel).id, "deepseek-pro");
});
});
test("a thrown stream error after content reaches the caller unchanged", async () => {
const failure = apiError(500);
// Pull-based, so the content part is delivered before the stream errors.
let pulls = 0;
const stream = new ReadableStream<unknown>({
pull(controller) {
pulls += 1;
if (pulls === 1) controller.enqueue({ type: "text-delta", delta: "半句" });
else controller.error(failure);
},
});
const { main, backup } = withFallback(async () => ({ stream }) as unknown as Result);
const result = await main.model.doStream(options());
await assert.rejects(readAll(result.stream as ReadableStream<unknown>), /provider answered 500/);
assert.equal(backup.calls(), 0);
});
test("without a fallback, or when the fallback fails too, the original error stands", async () => {
const lone = pooled("deepseek-pro", async () => { throw apiError(503); });
await assert.rejects(lone.model.doStream(options()), /provider answered 503/);
const broken = pooled("claude-backup", async () => { throw apiError(500); });
const main = pooled("deepseek-pro", async () => { throw apiError(503); }, async () => ({ model: broken.model, served: fallbackServed }));
await withModelServeScope(async () => {
await assert.rejects(main.model.doStream(options()), /provider answered 503/);
assert.equal(broken.calls(), 1, "the fallback is tried once and never hands on again");
assert.equal(servedModel(primaryModel).id, "deepseek-pro");
});
});
test("outside a scope the switch still answers; settlement then keeps the requested model", async () => {
const { main, backup } = withFallback(async () => { throw apiError(503); });
await main.model.doStream(options());
assert.equal(backup.calls(), 1);
assert.equal(servedModel(primaryModel).id, "deepseek-pro");
});
test("the catalog wires the admin's fallback model into every published model", () => {
const catalog = readFileSync(new URL("../src/lib/model-catalog.ts", import.meta.url), "utf8");
assert.match(catalog, /v\.fallback_model_id/);
assert.match(catalog, /fallback: \(\) => resolveFallback\(fallbackId\)/);
// Each settlement path names the model that served the calls.
for (const file of ["lib/consult/settlement.ts", "lib/personal-report-worker.ts", "lib/annual-report-server.ts", "lib/synastry-full-run.ts", "lib/personal-report-route-core.ts", "app/api/reports/route.ts"]) {
assert.match(readFileSync(new URL(`../src/${file}`, import.meta.url), "utf8"), /servedModel|servedUsageModel/, file);
}
for (const file of ["app/api/consult/route.ts", "app/api/reports/route.ts", "lib/personal-report-worker.ts", "lib/synastry-full-run.ts"]) {
assert.match(readFileSync(new URL(`../src/${file}`, import.meta.url), "utf8"), /withModelServeScope\(/, file);
}
});
test("暂停聊天 is an emergency stop: off unless turned on, checked before any credit is reserved", () => {
const flag = KNOWN_FEATURE_FLAGS.find((item) => item.key === "ops.chat_paused");
assert.ok(flag);
assert.equal(flag.label, "暂停聊天");
assert.match(flagEffect(flag), /^打开时:/);
assert.match(flagEffect(flag), /不扣点数/);
const pause = readFileSync(new URL("../src/lib/chat-pause.ts", import.meta.url), "utf8");
// A failed read keeps chat open.
assert.match(pause, /catch \{\s*return false;/);
const route = readFileSync(new URL("../src/app/api/consult/route.ts", import.meta.url), "utf8");
const paused = route.indexOf("if (await isChatPaused())");
assert.ok(paused > 0);
assert.ok(paused < route.indexOf("createServerSupabaseClient()"), "checked before the session, the user or any reservation");
assert.ok(paused < route.indexOf("begin_consultation_credit") || route.indexOf("begin_consultation_credit") === -1);
});