workflow-model-failure-policy.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import { describe, expect, it } from "vitest";
  2. import { ModelErrorCode, ModelFailureReason, ModelRetryBudget } from "@zcode/contracts";
  3. import { AiSdkModelAdapterError } from "../src/model/errors.js";
  4. import type { ClassifiedModelFailure } from "../src/model/failure-classifier.js";
  5. import {
  6. WORKFLOW_UNRECOGNIZED_CODE_MAX_CONSECUTIVE,
  7. inspectWorkflowModelFailure,
  8. isPlausibleQuotaResetAt,
  9. nextUnrecognizedCodeStreak,
  10. parseQuotaResetAt,
  11. resolveWorkflowModelFailurePolicy,
  12. retryAllowedByFailurePolicy,
  13. } from "../src/model/workflow-model-failure-policy.js";
  14. // apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Terminal states」:Stop 集逐行一例,其余一切 retry。
  15. function failure(
  16. overrides: Partial<ClassifiedModelFailure> & Pick<ClassifiedModelFailure, "reason">,
  17. ): ClassifiedModelFailure {
  18. return {
  19. code: ModelErrorCode.ModelRequestFailed,
  20. message: "x",
  21. retryReason: "network_error",
  22. retryable: false,
  23. ...overrides,
  24. };
  25. }
  26. describe("resolveWorkflowModelFailurePolicy", () => {
  27. it("Stop 集:认证 / 未配置 / 模型不可用 / 请求无效 / 配额", () => {
  28. expect(
  29. resolveWorkflowModelFailurePolicy(failure({ reason: ModelFailureReason.AuthFailed }), "1006"),
  30. ).toEqual({
  31. decision: "stop",
  32. kind: "auth",
  33. });
  34. expect(
  35. resolveWorkflowModelFailurePolicy(failure({ reason: ModelFailureReason.AuthFailed }), "3007"),
  36. ).toEqual({
  37. decision: "stop",
  38. kind: "auth",
  39. });
  40. expect(
  41. resolveWorkflowModelFailurePolicy(
  42. failure({ reason: ModelFailureReason.ProviderNotConfigured }),
  43. undefined,
  44. ),
  45. ).toEqual({ decision: "stop", kind: "not_configured" });
  46. expect(
  47. resolveWorkflowModelFailurePolicy(
  48. failure({ code: ModelErrorCode.ModelConfigMissing, reason: ModelFailureReason.Unknown }),
  49. undefined,
  50. ),
  51. ).toEqual({ decision: "stop", kind: "not_configured" });
  52. expect(
  53. resolveWorkflowModelFailurePolicy(
  54. failure({ code: ModelErrorCode.ModelNotFound, reason: ModelFailureReason.InvalidRequest }),
  55. "3006",
  56. ),
  57. ).toEqual({ decision: "stop", kind: "model_unavailable" });
  58. expect(
  59. resolveWorkflowModelFailurePolicy(
  60. failure({
  61. code: ModelErrorCode.InvalidModelRequest,
  62. reason: ModelFailureReason.InvalidRequest,
  63. }),
  64. "3001",
  65. ),
  66. ).toEqual({ decision: "stop", kind: "invalid_request" });
  67. expect(
  68. resolveWorkflowModelFailurePolicy(
  69. failure({
  70. code: ModelErrorCode.InvalidModelRequest,
  71. reason: ModelFailureReason.InvalidRequest,
  72. statusCode: 400,
  73. }),
  74. undefined,
  75. ),
  76. ).toEqual({ decision: "stop", kind: "invalid_request" });
  77. // 1005 在分类器里是 invalid_request:配额按码判、先于 reason。
  78. expect(
  79. resolveWorkflowModelFailurePolicy(
  80. failure({ reason: ModelFailureReason.InvalidRequest }),
  81. "1005",
  82. ),
  83. ).toEqual({
  84. decision: "stop",
  85. kind: "quota",
  86. });
  87. });
  88. it("并发上限 3008/3009/3010 与其余一切都是 retry(含分类器判不可重试的)", () => {
  89. for (const code of ["3008", "3009", "3010"]) {
  90. expect(
  91. resolveWorkflowModelFailurePolicy(
  92. failure({
  93. code: ModelErrorCode.ModelRateLimited,
  94. reason: ModelFailureReason.RateLimited,
  95. retryable: false,
  96. }),
  97. code,
  98. ),
  99. ).toEqual({ decision: "retry" });
  100. }
  101. for (const reason of [
  102. ModelFailureReason.RateLimited,
  103. ModelFailureReason.ProviderOverloaded,
  104. ModelFailureReason.ServerError,
  105. ModelFailureReason.NetworkError,
  106. ModelFailureReason.Timeout,
  107. ModelFailureReason.StreamIdleTimeout,
  108. ModelFailureReason.Unknown,
  109. ModelFailureReason.TlsError,
  110. ModelFailureReason.ProxyError,
  111. ]) {
  112. expect(resolveWorkflowModelFailurePolicy(failure({ reason }), undefined)).toEqual({
  113. decision: "retry",
  114. });
  115. }
  116. for (const code of ["1008", "1314", "1315", "2007"]) {
  117. expect(
  118. resolveWorkflowModelFailurePolicy(failure({ reason: ModelFailureReason.Unknown }), code),
  119. ).toEqual({
  120. decision: "retry",
  121. });
  122. }
  123. // 响应解析失败也被分类器标成 invalid_request,但那不是 provider 拒绝请求:再问一次。
  124. expect(
  125. resolveWorkflowModelFailurePolicy(
  126. failure({
  127. code: ModelErrorCode.InvalidModelResponse,
  128. reason: ModelFailureReason.InvalidRequest,
  129. }),
  130. undefined,
  131. ),
  132. ).toEqual({ decision: "retry" });
  133. });
  134. it("context exceeded 与 cancelled 各有自己的裁决", () => {
  135. expect(
  136. resolveWorkflowModelFailurePolicy(
  137. failure({ reason: ModelFailureReason.ContextExceeded }),
  138. "1261",
  139. ),
  140. ).toEqual({
  141. decision: "context_exceeded",
  142. });
  143. expect(
  144. resolveWorkflowModelFailurePolicy(
  145. failure({ reason: ModelFailureReason.Cancelled }),
  146. undefined,
  147. ),
  148. ).toEqual({
  149. decision: "cancelled",
  150. });
  151. });
  152. });
  153. describe("retryAllowedByFailurePolicy", () => {
  154. const busy = failure({
  155. code: ModelErrorCode.ModelRateLimited,
  156. reason: ModelFailureReason.RateLimited,
  157. retryable: false,
  158. });
  159. it("有界预算照旧读分类器的 retryable(主对话一字不动)", () => {
  160. expect(retryAllowedByFailurePolicy(busy, undefined, "3008")).toBe(false);
  161. expect(retryAllowedByFailurePolicy(busy, ModelRetryBudget.Default, "3008")).toBe(false);
  162. expect(retryAllowedByFailurePolicy({ ...busy, retryable: true }, undefined, undefined)).toBe(
  163. true,
  164. );
  165. });
  166. it("无上限预算读策略表", () => {
  167. expect(retryAllowedByFailurePolicy(busy, ModelRetryBudget.Unbounded, "3008")).toBe(true);
  168. expect(
  169. retryAllowedByFailurePolicy(
  170. failure({ reason: ModelFailureReason.AuthFailed }),
  171. ModelRetryBudget.Unbounded,
  172. "1006",
  173. ),
  174. ).toBe(false);
  175. expect(retryAllowedByFailurePolicy(busy, ModelRetryBudget.Unbounded, "1308")).toBe(false);
  176. });
  177. });
  178. describe("inspectWorkflowModelFailure", () => {
  179. it("按形状读 adapter 错误(直接或一层 cause),带出拼 ProviderStop 要的事实", () => {
  180. const adapterError = new AiSdkModelAdapterError(
  181. ModelErrorCode.ModelRateLimited,
  182. "[1308] 已达到 5 小时的使用上限",
  183. {
  184. context: {
  185. reason: "rate_limited",
  186. retryable: false,
  187. providerCode: 1308,
  188. providerId: "account:bigmodel-coding-plan",
  189. modelId: "glm-5.3",
  190. retryAfterMs: 60_000,
  191. },
  192. },
  193. );
  194. const direct = inspectWorkflowModelFailure(adapterError);
  195. expect(direct).toMatchObject({
  196. policy: { decision: "stop", kind: "quota" },
  197. reason: "rate_limited",
  198. providerCode: "1308",
  199. providerId: "account:bigmodel-coding-plan",
  200. modelId: "glm-5.3",
  201. rawMessage: "[1308] 已达到 5 小时的使用上限",
  202. });
  203. expect(direct?.resetAt).toBeGreaterThan(Date.now());
  204. const wrapped = new Error("Subagent turn failed", { cause: adapterError });
  205. expect(inspectWorkflowModelFailure(wrapped)?.policy).toEqual({
  206. decision: "stop",
  207. kind: "quota",
  208. });
  209. });
  210. it("并发上限是 retry;非模型层错误返回 undefined", () => {
  211. const busy = new AiSdkModelAdapterError(
  212. ModelErrorCode.ModelRateLimited,
  213. "user concurrency limit exceeded",
  214. {
  215. context: { reason: "rate_limited", retryable: false, providerCode: "3008" },
  216. },
  217. );
  218. expect(inspectWorkflowModelFailure(busy)).toMatchObject({
  219. policy: { decision: "retry" },
  220. providerCode: "3008",
  221. });
  222. expect(inspectWorkflowModelFailure(new Error("tool crashed"))).toBeUndefined();
  223. expect(inspectWorkflowModelFailure(undefined)).toBeUndefined();
  224. // 没有 reason 的 adapter 错误(构造期)也不归模型层。
  225. expect(
  226. inspectWorkflowModelFailure(
  227. new AiSdkModelAdapterError(ModelErrorCode.ModelRequestFailed, "x", { context: {} }),
  228. ),
  229. ).toBeUndefined();
  230. });
  231. });
  232. // 分类器不认识的业务码(reason = unknown,如 2026-10-16 事故里的 1113):原先无限重试,一个确定性的
  233. // 服务端拒绝会让 run 永远挂着、只剩 stall 通知。现在同一次请求里它**连续**出现到第 N 次时停下(kind
  234. // other,可 Resume);网络错误、5xx、限流照旧无限重试,并让连续计数从零重数(MR !3072 评审 CR-02)。
  235. describe("unrecognized provider codes", () => {
  236. const unknown = failure({ reason: ModelFailureReason.Unknown });
  237. const network = failure({ reason: ModelFailureReason.NetworkError });
  238. const limit = WORKFLOW_UNRECOGNIZED_CODE_MAX_CONSECUTIVE;
  239. /** 按 runner 的做法逐次更新连续计数,返回每一次的策略裁决。 */
  240. function decide(sequence: readonly { failure: ClassifiedModelFailure; code?: string }[]) {
  241. let streak = 0;
  242. return sequence.map(({ failure: item, code }) => {
  243. streak = nextUnrecognizedCodeStreak(streak, item, code);
  244. return resolveWorkflowModelFailurePolicy(item, code, streak).decision;
  245. });
  246. }
  247. it("is 10 in a row", () => {
  248. expect(limit).toBe(10);
  249. });
  250. it("retries below the limit and stops at it", () => {
  251. expect(resolveWorkflowModelFailurePolicy(unknown, "1113", limit - 1)).toEqual({
  252. decision: "retry",
  253. });
  254. expect(resolveWorkflowModelFailurePolicy(unknown, "1113", limit)).toEqual({
  255. decision: "stop",
  256. kind: "other",
  257. });
  258. expect(resolveWorkflowModelFailurePolicy(unknown, "1314", limit + 5)).toEqual({
  259. decision: "stop",
  260. kind: "other",
  261. });
  262. });
  263. it("counts only consecutive unknown codes: any other failure starts the count again", () => {
  264. expect(nextUnrecognizedCodeStreak(0, unknown, "1113")).toBe(1);
  265. expect(nextUnrecognizedCodeStreak(4, unknown, "1113")).toBe(5);
  266. expect(nextUnrecognizedCodeStreak(4, network, undefined)).toBe(0);
  267. expect(nextUnrecognizedCodeStreak(4, unknown, undefined)).toBe(0);
  268. expect(nextUnrecognizedCodeStreak(4, network, "1234")).toBe(0);
  269. });
  270. it("does not stop on one unknown code after nine network errors", () => {
  271. const decisions = decide([
  272. ...Array.from({ length: limit - 1 }, () => ({ failure: network })),
  273. { failure: unknown, code: "1113" },
  274. ]);
  275. expect(decisions.every((decision) => decision === "retry")).toBe(true);
  276. });
  277. it("does not stop while unknown codes alternate with network errors", () => {
  278. const decisions = decide(
  279. Array.from({ length: limit * 3 }, (_, index) =>
  280. index % 2 === 0 ? { failure: unknown, code: "1113" } : { failure: network },
  281. ),
  282. );
  283. expect(decisions.every((decision) => decision === "retry")).toBe(true);
  284. });
  285. it("stops on the 10th unknown code in a row, even after earlier network errors", () => {
  286. const decisions = decide([
  287. { failure: network },
  288. { failure: network },
  289. ...Array.from({ length: limit }, () => ({ failure: unknown, code: "1113" })),
  290. ]);
  291. expect(decisions.slice(0, -1).every((decision) => decision === "retry")).toBe(true);
  292. expect(decisions.at(-1)).toBe("stop");
  293. });
  294. it("keeps retrying network, server and rate-limit failures, and an unknown reason with no code", () => {
  295. for (const reason of [
  296. ModelFailureReason.NetworkError,
  297. ModelFailureReason.ServerError,
  298. ModelFailureReason.RateLimited,
  299. ModelFailureReason.Timeout,
  300. ]) {
  301. expect(resolveWorkflowModelFailurePolicy(failure({ reason }), "1234", 50)).toEqual({
  302. decision: "retry",
  303. });
  304. }
  305. expect(resolveWorkflowModelFailurePolicy(unknown, undefined, 50)).toEqual({
  306. decision: "retry",
  307. });
  308. });
  309. it("caps the runner gate for workflow traffic only", () => {
  310. expect(
  311. retryAllowedByFailurePolicy(unknown, ModelRetryBudget.Unbounded, "1113", limit - 1),
  312. ).toBe(true);
  313. expect(retryAllowedByFailurePolicy(unknown, ModelRetryBudget.Unbounded, "1113", limit)).toBe(
  314. false,
  315. );
  316. // 有界预算(主对话)照旧只读分类器的 retryable,与连续计数无关。
  317. expect(retryAllowedByFailurePolicy(unknown, undefined, "1113", 1)).toBe(false);
  318. });
  319. it("reads the streak from the adapter error, so the driver stops where the runner gave up", () => {
  320. const at = (context: Record<string, unknown>) =>
  321. inspectWorkflowModelFailure(
  322. new AiSdkModelAdapterError(ModelErrorCode.ModelRequestFailed, "[1113] 账户异常", {
  323. context: { providerCode: 1113, reason: "unknown", retryable: false, ...context },
  324. }),
  325. )?.policy;
  326. expect(at({ unrecognizedCodeStreak: limit - 1 })).toEqual({ decision: "retry" });
  327. expect(at({ unrecognizedCodeStreak: limit })).toEqual({ decision: "stop", kind: "other" });
  328. // 尝试次数不再是判据:第 10 次尝试、但未知码只连续出现了 1 次,照旧重试。
  329. expect(at({ attempt: limit, unrecognizedCodeStreak: 1 })).toEqual({ decision: "retry" });
  330. });
  331. });
  332. // 额度停止的重置时刻(docs/dynamic-workflow/... 「Resuming after a quota reset」):Retry-After 优先;
  333. // 没有时从 provider 原文里读「您的限额将在 YYYY-MM-DD HH:MM:SS 重置」。时刻按北京时间解释——
  334. // 文案来自 bigmodel 服务端,时间不带时区(2026-10 线上样本,如「将在 2026-10-15 18:50:42 重置」)。
  335. describe("quota reset time", () => {
  336. const now = Date.parse("2026-10-15T08:00:00.000Z"); // 北京时间 16:00
  337. it("reads the reset time from the provider's message, as Beijing time", () => {
  338. expect(
  339. parseQuotaResetAt(
  340. "[1308] 已达到 5 小时的使用上限。您的限额将在 2026-10-15 18:50:42 重置",
  341. now,
  342. ),
  343. ).toBe(Date.parse("2026-10-15T10:50:42.000Z"));
  344. expect(
  345. parseQuotaResetAt("您已达到每周/每月使用上限,您的限额将在 2026-10-20 00:00:00 重置", now),
  346. ).toBe(Date.parse("2026-10-19T16:00:00.000Z"));
  347. // 线上原文的完整形态:业务码、文案、请求 id 各占一对方括号;请求 id 的数字串不是时间。
  348. expect(
  349. parseQuotaResetAt(
  350. "[1308][已达到 5 小时的使用上限。您的限额将在 2026-10-15 18:50:42 重置。][20261015175300b9eb69fdbe0f4b93]",
  351. now,
  352. ),
  353. ).toBe(Date.parse("2026-10-15T10:50:42.000Z"));
  354. });
  355. it("ignores messages without a reset time, and times far outside a plausible window", () => {
  356. expect(parseQuotaResetAt("insufficient_quota", now)).toBeUndefined();
  357. expect(parseQuotaResetAt("您的限额将在 2019-01-01 00:00:00 重置", now)).toBeUndefined();
  358. expect(parseQuotaResetAt("您的限额将在 2027-06-01 00:00:00 重置", now)).toBeUndefined();
  359. });
  360. it("fills resetAt from the message when there is no Retry-After", () => {
  361. const inspected = inspectWorkflowModelFailure(
  362. new AiSdkModelAdapterError(
  363. ModelErrorCode.ModelRateLimited,
  364. "[1308] 已达到 5 小时的使用上限。您的限额将在 2099-01-01 00:00:00 重置",
  365. { context: { reason: "rate_limited", retryable: false, providerCode: "1308" } },
  366. ),
  367. );
  368. // 2099 远超合理窗口:不填,比填一个荒谬的时刻好。
  369. expect(inspected?.resetAt).toBeUndefined();
  370. const soon = new Date(Date.now() + 2 * 60 * 60 * 1000);
  371. const beijing = new Date(soon.getTime() + 8 * 60 * 60 * 1000).toISOString();
  372. const text = `${beijing.slice(0, 10)} ${beijing.slice(11, 19)}`;
  373. const fromMessage = inspectWorkflowModelFailure(
  374. new AiSdkModelAdapterError(
  375. ModelErrorCode.ModelRateLimited,
  376. `[1308] 已达到 5 小时的使用上限。您的限额将在 ${text} 重置`,
  377. { context: { reason: "rate_limited", retryable: false, providerCode: "1308" } },
  378. ),
  379. );
  380. expect(fromMessage?.resetAt).toBe(Math.floor(soon.getTime() / 1000) * 1000);
  381. });
  382. // MR !3072 第 2 轮评审 SG-01:Retry-After 与原文共用同一个合理窗口。
  383. it("ignores a Retry-After outside the plausible window, and reads the message instead", () => {
  384. const quotaError = (retryAfterMs: number, message = "[1308] 已达到 5 小时的使用上限") =>
  385. inspectWorkflowModelFailure(
  386. new AiSdkModelAdapterError(ModelErrorCode.ModelRateLimited, message, {
  387. context: { reason: "rate_limited", retryable: false, providerCode: "1308", retryAfterMs },
  388. }),
  389. );
  390. const thirtyYears = 30 * 365 * 24 * 60 * 60 * 1000;
  391. for (const retryAfterMs of [thirtyYears, 36 * 24 * 60 * 60 * 1000, -60_000, 0, NaN, Infinity]) {
  392. expect(quotaError(retryAfterMs)?.resetAt).toBeUndefined();
  393. }
  394. // header 不可信、原文里有可信的时刻:用原文的。
  395. const soon = new Date(Date.now() + 2 * 60 * 60 * 1000);
  396. const beijing = new Date(soon.getTime() + 8 * 60 * 60 * 1000).toISOString();
  397. const text = `${beijing.slice(0, 10)} ${beijing.slice(11, 19)}`;
  398. expect(quotaError(thirtyYears, `[1308] 您的限额将在 ${text} 重置`)?.resetAt).toBe(
  399. Math.floor(soon.getTime() / 1000) * 1000,
  400. );
  401. // 窗口上沿以内(35 天)照常采用 header。
  402. const before = Date.now();
  403. const monthly = quotaError(30 * 24 * 60 * 60 * 1000)?.resetAt;
  404. expect(monthly).toBeGreaterThanOrEqual(before + 30 * 24 * 60 * 60 * 1000);
  405. });
  406. it("judges plausibility with one window for both sources", () => {
  407. const now = Date.parse("2026-10-15T08:00:00.000Z");
  408. const day = 24 * 60 * 60 * 1000;
  409. expect(isPlausibleQuotaResetAt(now + 35 * day, now)).toBe(true);
  410. expect(isPlausibleQuotaResetAt(now + 35 * day + 1, now)).toBe(false);
  411. expect(isPlausibleQuotaResetAt(now - day, now)).toBe(true);
  412. expect(isPlausibleQuotaResetAt(now - day - 1, now)).toBe(false);
  413. expect(isPlausibleQuotaResetAt(Number.NaN, now)).toBe(false);
  414. });
  415. it("keeps Retry-After first when both are present", () => {
  416. const before = Date.now();
  417. const inspected = inspectWorkflowModelFailure(
  418. new AiSdkModelAdapterError(
  419. ModelErrorCode.ModelRateLimited,
  420. "[1308] 您的限额将在 2026-10-15 18:50:42 重置",
  421. {
  422. context: {
  423. reason: "rate_limited",
  424. retryable: false,
  425. providerCode: "1308",
  426. retryAfterMs: 60_000,
  427. },
  428. },
  429. ),
  430. );
  431. expect(inspected?.resetAt).toBeGreaterThanOrEqual(before + 60_000);
  432. expect(inspected?.resetAt).toBeLessThan(before + 120_000);
  433. });
  434. });