command-inbox.test.ts 25 KB

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