command-inbox.test.ts 23 KB

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