command-inbox.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. // Command inbox 单测(M2,10-protocol-spec §6.2/§6.3 的 ACK 裁决表)。
  2. import { describe, expect, it, vi } from "vitest";
  3. import type {
  4. CommandAck,
  5. CommandEnvelope,
  6. ConversationInputIntent,
  7. } from "@zcode/shared/zcode-protocol-v4";
  8. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  9. import type { CommandInboxHost } from "../src/zcode-protocol-v4/command-inbox.js";
  10. import { CommandInbox } from "../src/zcode-protocol-v4/command-inbox.js";
  11. function makeHost(overrides: Partial<CommandInboxHost> = {}): CommandInboxHost {
  12. return {
  13. getRevision: () => 7,
  14. getLogEpoch: () => "epoch-current",
  15. ...overrides,
  16. };
  17. }
  18. function envelope(partial: Partial<CommandEnvelope> = {}): CommandEnvelope {
  19. return {
  20. commandId: "cmd-1",
  21. clientId: "client-a",
  22. sessionId: "s-1",
  23. type: "sendText",
  24. payload: { text: "hello" },
  25. issuedAt: 1,
  26. ...partial,
  27. } as CommandEnvelope;
  28. }
  29. describe("CommandInbox ACK 裁决", () => {
  30. it("cold preparation runs after deduplication inside session admission", async () => {
  31. let revision: number | null = null;
  32. const prepareDecision = vi.fn(async () => {
  33. revision = 0;
  34. });
  35. const inbox = new CommandInbox(makeHost({ getRevision: () => revision, prepareDecision }));
  36. const command = envelope({ type: "deleteSession", payload: {} });
  37. const first = await inbox.handle(command);
  38. expect(first.kind).toBe("execute");
  39. if (first.kind !== "execute") return;
  40. revision = null;
  41. first.settle({ status: "accepted" });
  42. const retry = await inbox.handle(command);
  43. expect(retry.ack.status).toBe("duplicate");
  44. expect(prepareDecision).toHaveBeenCalledTimes(1);
  45. });
  46. it("合法命令 → accepted,revisionAtDecision = 当前 revision", async () => {
  47. const inbox = new CommandInbox(makeHost());
  48. const outcome = await inbox.handle(envelope());
  49. expect(outcome.kind).toBe("execute");
  50. if (outcome.kind !== "execute") return;
  51. expect(outcome.ack).toEqual({
  52. commandId: "cmd-1",
  53. status: "accepted",
  54. revisionAtDecision: 7,
  55. });
  56. });
  57. it("payload 非法 → rejected proto.invalidPayload", async () => {
  58. const inbox = new CommandInbox(makeHost());
  59. const outcome = await inbox.handle(envelope({ payload: { nope: true } }));
  60. expect(outcome.kind).toBe("ack");
  61. if (outcome.kind !== "ack") return;
  62. expect(outcome.ack.status).toBe("rejected");
  63. expect(outcome.ack.reasonCode).toBe("proto.invalidPayload");
  64. });
  65. it("未知会话 → rejected proto.sessionNotFound", async () => {
  66. const inbox = new CommandInbox(makeHost({ getRevision: () => null }));
  67. const outcome = await inbox.handle(envelope());
  68. expect(outcome.kind).toBe("ack");
  69. if (outcome.kind !== "ack") return;
  70. expect(outcome.ack.reasonCode).toBe("proto.sessionNotFound");
  71. });
  72. it("CAS 命令缺 revision/epoch → invalid;旧 epoch 优先于旧 revision稳定 stale", async () => {
  73. const inbox = new CommandInbox(makeHost());
  74. const missing = await inbox.handle(
  75. envelope({ type: "setAutoDrain", payload: { autoDrain: true } }),
  76. );
  77. expect(missing.kind).toBe("ack");
  78. if (missing.kind !== "ack") return;
  79. expect(missing.ack.reasonCode).toBe("proto.invalidPayload");
  80. const stale = await inbox.handle(
  81. envelope({
  82. commandId: "cmd-2",
  83. type: "retryTurn",
  84. payload: { target: { rowId: 4, entityId: "entity-4" } },
  85. baseRevision: 3,
  86. baseLogEpoch: "epoch-old",
  87. }),
  88. );
  89. expect(stale.kind).toBe("ack");
  90. if (stale.kind !== "ack") return;
  91. expect(stale.ack.status).toBe("stale");
  92. expect(stale.ack.reasonCode).toBe("proto.staleLogEpoch");
  93. expect(stale.ack.revisionAtDecision).toBe(7);
  94. const staleRevision = await inbox.handle(
  95. envelope({
  96. commandId: "cmd-3",
  97. type: "retryTurn",
  98. payload: { target: { rowId: 4, entityId: "entity-4" } },
  99. baseRevision: 3,
  100. baseLogEpoch: "epoch-current",
  101. }),
  102. );
  103. expect(staleRevision.kind).toBe("ack");
  104. if (staleRevision.kind === "ack") {
  105. expect(staleRevision.ack).toMatchObject({
  106. status: "stale",
  107. reasonCode: "proto.staleRevision",
  108. });
  109. }
  110. });
  111. it("row target entity mismatch stale;当前 entity 但 action 不可用 rejected", async () => {
  112. const inbox = new CommandInbox(
  113. makeHost({
  114. validateRowTarget: (env) => {
  115. const target = (env.payload as { target: { entityId: string } }).target;
  116. return target.entityId === "entity-current"
  117. ? { verdict: "reject", reasonCode: "guard.actionUnavailable" }
  118. : { verdict: "stale", reasonCode: "proto.staleTarget" };
  119. },
  120. }),
  121. );
  122. const targetEnvelope = (commandId: string, entityId: string): CommandEnvelope =>
  123. envelope({
  124. commandId,
  125. type: "retryTurn",
  126. payload: { target: { rowId: 8, entityId } },
  127. baseRevision: 7,
  128. baseLogEpoch: "epoch-current",
  129. });
  130. const stale = await inbox.handle(targetEnvelope("cmd-stale-target", "entity-reused"));
  131. expect(stale.kind).toBe("ack");
  132. if (stale.kind === "ack") {
  133. expect(stale.ack).toMatchObject({
  134. status: "stale",
  135. reasonCode: "proto.staleTarget",
  136. });
  137. }
  138. const rejected = await inbox.handle(targetEnvelope("cmd-no-action", "entity-current"));
  139. expect(rejected.kind).toBe("ack");
  140. if (rejected.kind === "ack") {
  141. expect(rejected.ack).toMatchObject({
  142. status: "rejected",
  143. reasonCode: "guard.actionUnavailable",
  144. });
  145. }
  146. });
  147. it("guard reject / noop 按宿主裁决透传(晚到 stop = noop,§6.3)", async () => {
  148. const inbox = new CommandInbox(
  149. makeHost({
  150. guard: (env) =>
  151. env.type === "stop"
  152. ? { verdict: "noop", reasonCode: "proto.alreadyStopping" }
  153. : { verdict: "reject", reasonCode: "guard.latestQueryEditOnly" },
  154. }),
  155. );
  156. const noop = await inbox.handle(envelope({ type: "stop", payload: {} }));
  157. expect(noop.kind).toBe("ack");
  158. if (noop.kind !== "ack") return;
  159. expect(noop.ack.status).toBe("noop");
  160. expect(noop.ack.reasonCode).toBe("proto.alreadyStopping");
  161. const rejected = await inbox.handle(envelope({ commandId: "cmd-2" }));
  162. expect(rejected.kind).toBe("ack");
  163. if (rejected.kind !== "ack") return;
  164. expect(rejected.ack.status).toBe("rejected");
  165. expect(rejected.ack.reasonCode).toBe("guard.latestQueryEditOnly");
  166. });
  167. });
  168. describe("CommandInbox 幂等(§6.2/§6.3)", () => {
  169. it("同 commandId 网络重试:settle 后 → duplicate 回放 result,不重放副作用", async () => {
  170. const inbox = new CommandInbox(makeHost());
  171. const first = await inbox.handle(
  172. envelope({ type: "createSession", sessionId: null, payload: { workspaceId: "w" } }),
  173. );
  174. expect(first.kind).toBe("execute");
  175. if (first.kind !== "execute") return;
  176. first.settle({
  177. status: "accepted",
  178. result: { type: "createSession", sessionId: "s-new" },
  179. });
  180. const retry = await inbox.handle(
  181. envelope({ type: "createSession", sessionId: null, payload: { workspaceId: "w" } }),
  182. );
  183. expect(retry.kind).toBe("ack");
  184. if (retry.kind !== "ack") return;
  185. expect(retry.ack.status).toBe("duplicate");
  186. expect(retry.ack.result).toEqual({ type: "createSession", sessionId: "s-new" });
  187. });
  188. it("在途重复等待同一 final-result promise,不回无 result 的初始 ACK", async () => {
  189. const inbox = new CommandInbox(makeHost());
  190. const first = await inbox.handle(envelope());
  191. expect(first.kind).toBe("execute");
  192. if (first.kind !== "execute") return;
  193. let retryResolved = false;
  194. const retryPromise = inbox.handle(envelope()).then((outcome) => {
  195. retryResolved = true;
  196. return outcome;
  197. });
  198. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  199. expect(retryResolved).toBe(false);
  200. first.settle({
  201. status: "accepted",
  202. result: { type: "forkAssistant", sessionId: "fork-child" },
  203. });
  204. const retry = await retryPromise;
  205. expect(retry.kind).toBe("ack");
  206. if (retry.kind !== "ack") return;
  207. expect(retry.ack.status).toBe("duplicate");
  208. expect(retry.ack.result).toEqual({ type: "forkAssistant", sessionId: "fork-child" });
  209. });
  210. it("noop 结论进幂等表:同 commandId 重试 → duplicate 携带原 reasonCode", async () => {
  211. const inbox = new CommandInbox(
  212. makeHost({
  213. guard: () => ({ verdict: "noop", reasonCode: "proto.alreadyResolved" }),
  214. }),
  215. );
  216. await inbox.handle(envelope());
  217. const retry = await inbox.handle(envelope());
  218. expect(retry.kind).toBe("ack");
  219. if (retry.kind !== "ack") return;
  220. expect(retry.ack.status).toBe("duplicate");
  221. expect(retry.ack.reasonCode).toBe("proto.alreadyResolved");
  222. });
  223. it("幂等表 LRU:超过 512 条后最老条目被淘汰,重发不再 duplicate", async () => {
  224. const inbox = new CommandInbox(makeHost());
  225. const first = await inbox.handle(envelope({ commandId: "cmd-0" }));
  226. expect(first.kind).toBe("execute");
  227. if (first.kind === "execute") first.settle({ status: "accepted" });
  228. for (let i = 1; i <= PROTOCOL_V4_LIMITS.idempotencyTablePerSession; i += 1) {
  229. const outcome = await inbox.handle(envelope({ commandId: `cmd-${i}` }));
  230. if (outcome.kind === "execute") outcome.settle({ status: "accepted" });
  231. }
  232. const resent = await inbox.handle(envelope({ commandId: "cmd-0" }));
  233. // cmd-0 已被淘汰 → 视为新命令重新受理(transcript 兜底属后续片)。
  234. expect(resent.kind).toBe("execute");
  235. });
  236. it("幂等表按 session 隔离:不同 session 同 commandId 互不影响", async () => {
  237. const inbox = new CommandInbox(makeHost());
  238. const [a, b] = await Promise.all([
  239. inbox.handle(envelope({ sessionId: "s-1" })),
  240. inbox.handle(envelope({ sessionId: "s-2" })),
  241. ]);
  242. expect(a.kind).toBe("execute");
  243. expect(b.kind).toBe("execute");
  244. });
  245. });
  246. function accepted(commandId: string, revisionAtDecision = 7): CommandAck {
  247. return { commandId, status: "accepted", revisionAtDecision };
  248. }
  249. function intent(commandId: string): ConversationInputIntent {
  250. return {
  251. sourceCommandId: commandId,
  252. queueItemId: `queue-${commandId}`,
  253. clientId: "client-a",
  254. kind: "sendText",
  255. text: `text-${commandId}`,
  256. attachments: [],
  257. delivery: { requested: "queue", admitted: "queue" },
  258. order: { admissionSeq: 1, queuePosition: 0 },
  259. steer: { state: "notRequested" },
  260. dispatch: { state: "queued" },
  261. admittedAt: 1,
  262. };
  263. }
  264. async function settleAccepted(inbox: CommandInbox, commandId: string): Promise<void> {
  265. const outcome = await inbox.handle(envelope({ commandId }));
  266. expect(outcome.kind).toBe("execute");
  267. if (outcome.kind === "execute") outcome.settle({ status: "accepted" });
  268. }
  269. describe("CommandInbox pinned facts 与持久化 fallback(§7.3)", () => {
  270. it("session 去激活只清 settled/admission 内存,in-flight pin 会拒绝清理", async () => {
  271. const inbox = new CommandInbox(makeHost());
  272. const settled = await inbox.handle(envelope({ commandId: "settled-before-deactivate" }));
  273. expect(settled.kind).toBe("execute");
  274. if (settled.kind === "execute") settled.settle({ status: "accepted" });
  275. const running = await inbox.handle(envelope({ commandId: "running-during-deactivate" }));
  276. expect(running.kind).toBe("execute");
  277. expect(inbox.hasPinnedSessionState("s-1")).toBe(true);
  278. expect(inbox.clearSession("s-1")).toBe(false);
  279. if (running.kind === "execute") running.settle({ status: "accepted" });
  280. expect(inbox.hasPinnedSessionState("s-1")).toBe(false);
  281. expect(inbox.clearSession("s-1")).toBe(true);
  282. const afterColdStart = await inbox.handle(envelope({ commandId: "settled-before-deactivate" }));
  283. expect(afterColdStart.kind).toBe("execute");
  284. if (afterColdStart.kind === "execute") {
  285. expect(afterColdStart.admissionSeq).toBe(1);
  286. afterColdStart.settle({ status: "accepted" });
  287. }
  288. });
  289. it(">512 settled churn 后新 in-flight 仍为 pinned,query 不会 unknown", async () => {
  290. const inbox = new CommandInbox(makeHost());
  291. for (let i = 0; i <= PROTOCOL_V4_LIMITS.idempotencyTablePerSession; i += 1) {
  292. await settleAccepted(inbox, `settled-${i}`);
  293. }
  294. const running = await inbox.handle(envelope({ commandId: "running-pinned" }));
  295. expect(running.kind).toBe("execute");
  296. const queryPromise = inbox.query([{ sessionId: "s-1", commandId: "running-pinned" }]);
  297. if (running.kind === "execute") {
  298. running.settle({
  299. status: "accepted",
  300. result: { type: "forkAssistant", sessionId: "fork-child" },
  301. });
  302. }
  303. const [query] = await queryPromise;
  304. expect(query?.result).toEqual({
  305. ...accepted("running-pinned"),
  306. result: { type: "forkAssistant", sessionId: "fork-child" },
  307. });
  308. });
  309. it("live queue/guide fact 在后续 >512 settled churn 中不被淘汰", async () => {
  310. const inbox = new CommandInbox(makeHost());
  311. const live = await inbox.handle(envelope({ commandId: "live-pinned" }));
  312. expect(live.kind).toBe("execute");
  313. if (live.kind !== "execute") return;
  314. inbox.pinLiveInput("s-1", intent("live-pinned"));
  315. live.settle({ status: "accepted" });
  316. for (let i = 0; i <= PROTOCOL_V4_LIMITS.idempotencyTablePerSession; i += 1) {
  317. await settleAccepted(inbox, `after-live-${i}`);
  318. }
  319. const [query] = await inbox.query([{ sessionId: "s-1", commandId: "live-pinned" }]);
  320. expect(query?.result).toEqual(accepted("live-pinned"));
  321. });
  322. it("settled LRU 淘汰后 execute 先回源 transcript,不再次执行", async () => {
  323. let transcriptVisible = false;
  324. const lookupTranscriptCommand = vi.fn((key: { commandId: string }) =>
  325. transcriptVisible && key.commandId === "evicted" ? accepted("evicted", 2) : null,
  326. );
  327. const inbox = new CommandInbox(makeHost({ lookupTranscriptCommand }));
  328. await settleAccepted(inbox, "evicted");
  329. for (let i = 0; i < PROTOCOL_V4_LIMITS.idempotencyTablePerSession; i += 1) {
  330. await settleAccepted(inbox, `churn-${i}`);
  331. }
  332. transcriptVisible = true;
  333. const retry = await inbox.handle(envelope({ commandId: "evicted" }));
  334. expect(retry.kind).toBe("ack");
  335. if (retry.kind === "ack") {
  336. expect(retry.ack).toMatchObject({ status: "duplicate", revisionAtDecision: 2 });
  337. }
  338. expect(lookupTranscriptCommand).toHaveBeenCalledWith({
  339. sessionId: "s-1",
  340. commandId: "evicted",
  341. });
  342. });
  343. it("用户删除的 queue input 在 >512 LRU churn 后命中 durable cancelled,不再执行", async () => {
  344. let cancelledVisible = false;
  345. const cancelled: CommandAck = {
  346. commandId: "removed-input",
  347. status: "failed",
  348. reasonCode: "fault.command.inputCancelled",
  349. revisionAtDecision: 0,
  350. };
  351. const lookupDiscardedCommand = vi.fn((key: { commandId: string }) =>
  352. cancelledVisible && key.commandId === "removed-input" ? cancelled : null,
  353. );
  354. const inbox = new CommandInbox(makeHost({ lookupDiscardedCommand }));
  355. await settleAccepted(inbox, "removed-input");
  356. for (let i = 0; i <= PROTOCOL_V4_LIMITS.idempotencyTablePerSession; i += 1) {
  357. await settleAccepted(inbox, `removed-churn-${i}`);
  358. }
  359. cancelledVisible = true;
  360. const retry = await inbox.handle(envelope({ commandId: "removed-input" }));
  361. expect(retry.kind).toBe("ack");
  362. if (retry.kind === "ack") expect(retry.ack).toEqual(cancelled);
  363. expect(lookupDiscardedCommand).toHaveBeenCalledWith({
  364. sessionId: "s-1",
  365. commandId: "removed-input",
  366. });
  367. });
  368. it("持久化优先级固定为 transcript → marker → child → discarded → unknown", async () => {
  369. const calls: string[] = [];
  370. const found = (source: string, result: CommandAck | null) => async () => {
  371. calls.push(source);
  372. return result;
  373. };
  374. const queryWith = async (hits: Partial<Record<string, CommandAck>>) => {
  375. calls.length = 0;
  376. const inbox = new CommandInbox(
  377. makeHost({
  378. lookupTranscriptCommand: found("transcript", hits.transcript ?? null),
  379. lookupTimelineCommand: found("marker", hits.marker ?? null),
  380. lookupChildCommand: found("child", hits.child ?? null),
  381. lookupDiscardedCommand: found("discarded", hits.discarded ?? null),
  382. }),
  383. );
  384. return (await inbox.query([{ sessionId: "s-1", commandId: "exact-id" }]))[0]?.result;
  385. };
  386. expect(
  387. await queryWith({ transcript: accepted("exact-id", 1), marker: accepted("exact-id", 2) }),
  388. ).toMatchObject({ revisionAtDecision: 1 });
  389. expect(calls).toEqual(["transcript"]);
  390. expect(
  391. await queryWith({ marker: accepted("exact-id", 2), child: accepted("exact-id", 3) }),
  392. ).toMatchObject({ revisionAtDecision: 2 });
  393. expect(calls).toEqual(["transcript", "marker"]);
  394. expect(
  395. await queryWith({ child: accepted("exact-id", 3), discarded: accepted("exact-id", 4) }),
  396. ).toMatchObject({ revisionAtDecision: 3 });
  397. expect(calls).toEqual(["transcript", "marker", "child"]);
  398. const discarded = {
  399. commandId: "exact-id",
  400. status: "failed" as const,
  401. reasonCode: "fault.command.inputDiscardedOnRestart",
  402. revisionAtDecision: 4,
  403. };
  404. expect(await queryWith({ discarded })).toEqual(discarded);
  405. expect(calls).toEqual(["transcript", "marker", "child", "discarded"]);
  406. expect(await queryWith({})).toBe("unknown");
  407. expect(calls).toEqual(["transcript", "marker", "child", "discarded"]);
  408. });
  409. it("unknown 不缓存,后续增量索引命中可直接收敛", async () => {
  410. let result: CommandAck | null = null;
  411. const inbox = new CommandInbox(makeHost({ lookupTranscriptCommand: () => result }));
  412. const key = { sessionId: "s-1", commandId: "later" };
  413. expect((await inbox.query([key]))[0]?.result).toBe("unknown");
  414. result = accepted("later");
  415. expect((await inbox.query([key]))[0]?.result).toEqual(accepted("later"));
  416. });
  417. it("持久化读取失败显式返回 fault.command.queryUnavailable", async () => {
  418. const inbox = new CommandInbox(
  419. makeHost({
  420. lookupTranscriptCommand: () => Promise.reject(new Error("sqlite busy")),
  421. }),
  422. );
  423. const [query] = await inbox.query([{ sessionId: "s-1", commandId: "cmd-error" }]);
  424. expect(query?.result).toEqual({
  425. commandId: "cmd-error",
  426. status: "failed",
  427. reasonCode: "fault.command.queryUnavailable",
  428. revisionAtDecision: 7,
  429. });
  430. });
  431. it("failed settled retry 保持 failed,不被 duplicate 覆盖", async () => {
  432. const inbox = new CommandInbox(makeHost());
  433. const first = await inbox.handle(envelope({ commandId: "failed-once" }));
  434. expect(first.kind).toBe("execute");
  435. if (first.kind !== "execute") return;
  436. first.settle({ status: "failed", reasonCode: "fault.command.executionFailed" });
  437. const retry = await inbox.handle(envelope({ commandId: "failed-once" }));
  438. expect(retry.kind).toBe("ack");
  439. if (retry.kind === "ack") {
  440. expect(retry.ack).toMatchObject({
  441. status: "failed",
  442. reasonCode: "fault.command.executionFailed",
  443. });
  444. }
  445. });
  446. it("fork/create child metadata 回放原 child sessionId,不创建第二个 child", async () => {
  447. const childFacts = new Map([
  448. [
  449. "s-1\0fork-command",
  450. {
  451. commandId: "fork-command",
  452. status: "accepted" as const,
  453. revisionAtDecision: 9,
  454. result: { type: "forkAssistant" as const, sessionId: "fork-child" },
  455. },
  456. ],
  457. [
  458. "@global\0create-command",
  459. {
  460. commandId: "create-command",
  461. status: "accepted" as const,
  462. revisionAtDecision: 0,
  463. result: { type: "createSession" as const, sessionId: "created-child" },
  464. },
  465. ],
  466. ]);
  467. const inbox = new CommandInbox(
  468. makeHost({
  469. lookupChildCommand: (key) =>
  470. childFacts.get(`${key.sessionId ?? "@global"}\0${key.commandId}`) ?? null,
  471. }),
  472. );
  473. const forkRetry = await inbox.handle(
  474. envelope({
  475. commandId: "fork-command",
  476. type: "forkAssistant",
  477. payload: { target: { rowId: 4, entityId: "assistant-4" } },
  478. baseRevision: 7,
  479. baseLogEpoch: "epoch-current",
  480. }),
  481. );
  482. const createRetry = await inbox.handle(
  483. envelope({
  484. commandId: "create-command",
  485. sessionId: null,
  486. type: "createSession",
  487. payload: { workspaceId: "/repo" },
  488. }),
  489. );
  490. expect(forkRetry.kind).toBe("ack");
  491. expect(createRetry.kind).toBe("ack");
  492. if (forkRetry.kind === "ack") {
  493. expect(forkRetry.ack.result).toEqual({ type: "forkAssistant", sessionId: "fork-child" });
  494. }
  495. if (createRetry.kind === "ack") {
  496. expect(createRetry.ack.result).toEqual({ type: "createSession", sessionId: "created-child" });
  497. }
  498. });
  499. });
  500. describe("CommandInbox single-flight 与 admission FIFO", () => {
  501. it("query + execute 同 key 竞态:execute pin 后 query 不会 unknown,重复只执行一次", async () => {
  502. let releaseLookup!: () => void;
  503. const lookupBlocked = new Promise<void>((resolve) => {
  504. releaseLookup = resolve;
  505. });
  506. let firstLookup = true;
  507. const inbox = new CommandInbox(
  508. makeHost({
  509. lookupTranscriptCommand: async () => {
  510. if (firstLookup) {
  511. firstLookup = false;
  512. await lookupBlocked;
  513. }
  514. return null;
  515. },
  516. }),
  517. );
  518. const raw = envelope({ commandId: "race" });
  519. const executePromise = inbox.handle(raw);
  520. const retryPromise = inbox.handle(raw);
  521. const queryPromise = inbox.query([{ sessionId: "s-1", commandId: "race" }]);
  522. releaseLookup();
  523. const execute = await executePromise;
  524. expect(execute.kind).toBe("execute");
  525. if (execute.kind === "execute") {
  526. execute.settle({
  527. status: "accepted",
  528. result: { type: "forkAssistant", sessionId: "race-child" },
  529. });
  530. }
  531. const [retry, query] = await Promise.all([retryPromise, queryPromise]);
  532. expect(retry.kind).toBe("ack");
  533. if (retry.kind === "ack") {
  534. expect(retry.ack).toEqual({
  535. ...accepted("race"),
  536. status: "duplicate",
  537. result: { type: "forkAssistant", sessionId: "race-child" },
  538. });
  539. }
  540. expect(query[0]?.result).toEqual({
  541. ...accepted("race"),
  542. result: { type: "forkAssistant", sessionId: "race-child" },
  543. });
  544. });
  545. it("同 session commandId 严格 FIFO,admissionSeq 单调;不同 session 可并行", async () => {
  546. const inbox = new CommandInbox(makeHost());
  547. const first = await inbox.handle(envelope({ commandId: "fifo-1" }));
  548. expect(first.kind).toBe("execute");
  549. if (first.kind !== "execute") return;
  550. expect(first.admissionSeq).toBe(1);
  551. let sameSessionResolved = false;
  552. const sameSession = inbox.handle(envelope({ commandId: "fifo-2" })).then((outcome) => {
  553. sameSessionResolved = true;
  554. return outcome;
  555. });
  556. await Promise.resolve();
  557. expect(sameSessionResolved).toBe(false);
  558. const otherSession = await inbox.handle(
  559. envelope({ sessionId: "s-2", commandId: "parallel-1" }),
  560. );
  561. expect(otherSession.kind).toBe("execute");
  562. if (otherSession.kind === "execute") {
  563. expect(otherSession.admissionSeq).toBe(1);
  564. otherSession.settle({ status: "accepted" });
  565. }
  566. first.settle({ status: "accepted" });
  567. const second = await sameSession;
  568. expect(second.kind).toBe("execute");
  569. if (second.kind === "execute") {
  570. expect(second.admissionSeq).toBe(2);
  571. second.settle({ status: "accepted" });
  572. }
  573. });
  574. it("failed settle 也释放 session FIFO,后续 command 不死锁", async () => {
  575. const inbox = new CommandInbox(makeHost());
  576. const first = await inbox.handle(envelope({ commandId: "fifo-failed-1" }));
  577. expect(first.kind).toBe("execute");
  578. if (first.kind !== "execute") return;
  579. let secondResolved = false;
  580. const secondPromise = inbox
  581. .handle(envelope({ commandId: "fifo-after-failed-2" }))
  582. .then((outcome) => {
  583. secondResolved = true;
  584. return outcome;
  585. });
  586. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  587. expect(secondResolved).toBe(false);
  588. first.settle({
  589. status: "failed",
  590. reasonCode: "fault.command.executionFailed",
  591. });
  592. const second = await secondPromise;
  593. expect(second.kind).toBe("execute");
  594. if (second.kind === "execute") second.settle({ status: "accepted" });
  595. });
  596. });