turn-execution-fallback.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { describe, expect, it } from "vitest";
  2. import { ModelErrorCode, ModelProtocolError, ModelRetryBudget } from "@zcode/contracts";
  3. import {
  4. matchExecutionSelectionCreationFallback,
  5. matchExecutionSelectionFallback,
  6. resolveExecutionFallbackCandidates,
  7. } from "../src/runtime/methods/turn-execution-fallback.js";
  8. import { resolveExecutionModelRetryBudget } from "../src/runtime/methods/turn-model.js";
  9. // docs/highspeed/highspeed-card-spec.md §2.2:加速请求任何失败都退回会话模型;卡过期按 3402 单独给原因。
  10. const HIGHSPEED_PROVIDER_ID = "account:zai-highspeed-card";
  11. const SESSION_PROVIDER_ID = "builtin:zai-coding-plan";
  12. const CARD_EXPIRED_CODE = "3402";
  13. const declaration = {
  14. providerId: HIGHSPEED_PROVIDER_ID,
  15. rules: [
  16. { reason: "highspeed_card_expired" as const, providerErrorCode: CARD_EXPIRED_CODE },
  17. { reason: "highspeed_request_failed" as const },
  18. ],
  19. };
  20. /** adapter 归一化后的错误形状:归因字段都在 context 里。 */
  21. function adapterError(
  22. context: Record<string, unknown>,
  23. message = "Model request failed.",
  24. code = "model_request_failed",
  25. ): Error {
  26. return Object.assign(new Error(message), {
  27. code,
  28. context: {
  29. providerId: HIGHSPEED_PROVIDER_ID,
  30. modelId: "GLM-5.3",
  31. source: "provider",
  32. ...context,
  33. },
  34. name: "AiSdkModelAdapterError",
  35. });
  36. }
  37. function match(
  38. error: unknown,
  39. overrides: Partial<Parameters<typeof matchExecutionSelectionFallback>[0]> = {},
  40. ) {
  41. return matchExecutionSelectionFallback({
  42. error,
  43. executionProviderId: HIGHSPEED_PROVIDER_ID,
  44. selectionFallback: declaration,
  45. turnAborted: false,
  46. ...overrides,
  47. });
  48. }
  49. describe("matchExecutionSelectionFallback", () => {
  50. it("卡过期错误码命中首条规则,原因为 highspeed_card_expired 并带回归因", () => {
  51. expect(match(adapterError({ providerCode: CARD_EXPIRED_CODE, statusCode: 400 }))).toEqual({
  52. reason: "highspeed_card_expired",
  53. providerErrorCode: CARD_EXPIRED_CODE,
  54. statusCode: 400,
  55. });
  56. });
  57. it.each([
  58. ["401 鉴权失败", { statusCode: 401, reason: "auth_failed", retryable: false }],
  59. ["429 限流", { statusCode: 429, reason: "rate_limited", retryable: true }],
  60. ["5xx", { statusCode: 503, reason: "server_error", retryable: true }],
  61. ["网络错误(无 HTTP 状态、无业务码)", { reason: "network_error", retryable: true }],
  62. ["流空闲超时", { reason: "stream_idle_timeout", retryable: true }],
  63. ["其他业务码", { providerCode: "1234", statusCode: 400 }],
  64. ])("%s 命中兜底规则,原因为 highspeed_request_failed", (_label, context) => {
  65. expect(match(adapterError(context))?.reason).toBe("highspeed_request_failed");
  66. });
  67. it("没有声明、用户取消或本步模型不是声明 provider 时不退回", () => {
  68. const error = adapterError({ statusCode: 500 });
  69. expect(match(error, { selectionFallback: undefined })).toBeUndefined();
  70. expect(match(error, { turnAborted: true })).toBeUndefined();
  71. expect(match(error, { executionProviderId: SESSION_PROVIDER_ID })).toBeUndefined();
  72. });
  73. it("失败归因明确指向其他 provider 时不退回", () => {
  74. expect(
  75. match(adapterError({ providerId: SESSION_PROVIDER_ID, statusCode: 500 })),
  76. ).toBeUndefined();
  77. });
  78. it("无上游归因或归因为本地 runtime 的失败不退回", () => {
  79. expect(match(new Error("event store append failed"))).toBeUndefined();
  80. expect(
  81. match(adapterError({ source: "runtime", reason: "persistence_failed" })),
  82. ).toBeUndefined();
  83. });
  84. it("上下文超窗不退回,交给 reactive compact", () => {
  85. expect(
  86. match(
  87. adapterError(
  88. { reason: "context_exceeded", statusCode: 400 },
  89. "Model request exceeded the provider context window.",
  90. "model_context_exceeded",
  91. ),
  92. ),
  93. ).toBeUndefined();
  94. });
  95. it("只声明错误码规则时,其他失败不退回;规则按声明顺序首个命中", () => {
  96. const expiredOnly = { providerId: HIGHSPEED_PROVIDER_ID, rules: [declaration.rules[0]!] };
  97. expect(
  98. match(adapterError({ statusCode: 500 }), { selectionFallback: expiredOnly }),
  99. ).toBeUndefined();
  100. expect(
  101. match(adapterError({ providerCode: CARD_EXPIRED_CODE }), { selectionFallback: expiredOnly })
  102. ?.reason,
  103. ).toBe("highspeed_card_expired");
  104. // 兜底规则排在前面会遮蔽后面的错误码规则:声明顺序就是优先级。
  105. const catchAllFirst = {
  106. providerId: HIGHSPEED_PROVIDER_ID,
  107. rules: [declaration.rules[1]!, declaration.rules[0]!],
  108. };
  109. expect(
  110. match(adapterError({ providerCode: CARD_EXPIRED_CODE }), { selectionFallback: catchAllFirst })
  111. ?.reason,
  112. ).toBe("highspeed_request_failed");
  113. });
  114. });
  115. describe("matchExecutionSelectionCreationFallback", () => {
  116. it.each([ModelErrorCode.ProviderNotFound, ModelErrorCode.ModelNotFound])(
  117. "%s 仅在 execution Selection 与声明 provider 相同时退回",
  118. (code) => {
  119. const error = new ModelProtocolError(code, "selection unavailable");
  120. expect(
  121. matchExecutionSelectionCreationFallback({
  122. error,
  123. selection: { providerId: HIGHSPEED_PROVIDER_ID, modelId: "GLM-5.3" },
  124. selectionFallback: declaration,
  125. selectionScope: "execution",
  126. }),
  127. ).toEqual({ reason: "highspeed_selection_unavailable" });
  128. expect(
  129. matchExecutionSelectionCreationFallback({
  130. error,
  131. selection: { providerId: SESSION_PROVIDER_ID, modelId: "GLM-5.3" },
  132. selectionFallback: declaration,
  133. selectionScope: "execution",
  134. }),
  135. ).toBeUndefined();
  136. },
  137. );
  138. it("普通 Selection 与其他创建错误不退回", () => {
  139. const selection = { providerId: HIGHSPEED_PROVIDER_ID, modelId: "GLM-5.3" };
  140. expect(
  141. matchExecutionSelectionCreationFallback({
  142. error: new ModelProtocolError(ModelErrorCode.ProviderNotFound, "missing"),
  143. selection,
  144. selectionFallback: declaration,
  145. selectionScope: undefined,
  146. }),
  147. ).toBeUndefined();
  148. expect(
  149. matchExecutionSelectionCreationFallback({
  150. error: new ModelProtocolError(ModelErrorCode.InvalidModelRequest, "invalid"),
  151. selection,
  152. selectionFallback: declaration,
  153. selectionScope: "execution",
  154. }),
  155. ).toBeUndefined();
  156. });
  157. });
  158. describe("resolveExecutionFallbackCandidates", () => {
  159. // spec §2.2:退回目标先取发起方声明的 target(抽卡时的提交选择),再取 runtime 会话常驻 Selection。
  160. const target = {
  161. providerId: SESSION_PROVIDER_ID,
  162. modelId: "GLM-5.3",
  163. options: { reasoningLevel: "low" },
  164. };
  165. const resident = { providerId: "user-provider", modelId: "user-model" };
  166. it("先取声明的 target,再取会话常驻 Selection", () => {
  167. expect(
  168. resolveExecutionFallbackCandidates({
  169. declaredTarget: target,
  170. executionProviderId: HIGHSPEED_PROVIDER_ID,
  171. sessionSelection: resident,
  172. }),
  173. ).toEqual([
  174. { source: "declared_target", selection: target },
  175. { source: "session_selection", selection: resident },
  176. ]);
  177. });
  178. it("没有 target 时只剩会话常驻 Selection;都没有时无候选", () => {
  179. expect(
  180. resolveExecutionFallbackCandidates({
  181. declaredTarget: undefined,
  182. executionProviderId: HIGHSPEED_PROVIDER_ID,
  183. sessionSelection: resident,
  184. }),
  185. ).toEqual([{ source: "session_selection", selection: resident }]);
  186. expect(
  187. resolveExecutionFallbackCandidates({
  188. declaredTarget: undefined,
  189. executionProviderId: HIGHSPEED_PROVIDER_ID,
  190. sessionSelection: undefined,
  191. }),
  192. ).toEqual([]);
  193. });
  194. it("候选不能是本轮 execution provider 本身;相同候选只保留一个", () => {
  195. // 退回同一个失败端点只会再失败一次;误声明成加速 provider 的 target 直接忽略。
  196. expect(
  197. resolveExecutionFallbackCandidates({
  198. declaredTarget: { providerId: HIGHSPEED_PROVIDER_ID, modelId: "GLM-5.3" },
  199. executionProviderId: HIGHSPEED_PROVIDER_ID,
  200. sessionSelection: target,
  201. }),
  202. ).toEqual([{ source: "session_selection", selection: target }]);
  203. expect(
  204. resolveExecutionFallbackCandidates({
  205. declaredTarget: target,
  206. executionProviderId: HIGHSPEED_PROVIDER_ID,
  207. sessionSelection: { ...target, options: { ...target.options } },
  208. }),
  209. ).toEqual([{ source: "declared_target", selection: target }]);
  210. });
  211. });
  212. describe("resolveExecutionModelRetryBudget", () => {
  213. it("带退回声明且 Selection 指向声明 provider 的执行句柄 0 次重试", () => {
  214. expect(
  215. resolveExecutionModelRetryBudget({
  216. selection: { providerId: HIGHSPEED_PROVIDER_ID, modelId: "GLM-5.3" },
  217. selectionFallback: declaration,
  218. }),
  219. ).toBe(ModelRetryBudget.SingleAttempt);
  220. });
  221. it("无声明、无 Selection 或 Selection 不是声明 provider 时沿用默认预算", () => {
  222. expect(
  223. resolveExecutionModelRetryBudget({
  224. selection: { providerId: HIGHSPEED_PROVIDER_ID, modelId: "GLM-5.3" },
  225. selectionFallback: undefined,
  226. }),
  227. ).toBeUndefined();
  228. expect(
  229. resolveExecutionModelRetryBudget({
  230. selection: { providerId: SESSION_PROVIDER_ID, modelId: "GLM-5.3" },
  231. selectionFallback: declaration,
  232. }),
  233. ).toBeUndefined();
  234. expect(
  235. resolveExecutionModelRetryBudget({ selection: undefined, selectionFallback: declaration }),
  236. ).toBeUndefined();
  237. });
  238. });