workflow-actor-transcript.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /**
  2. * 种子截断复制的幂等与「绝不写进已开跑会话」两条规则
  3. * (apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Driver side: boundaries and seeding」)。
  4. *
  5. * 走真 SQLite 会话存储:这两条规则的判据是消息 id 与消息条数,而 `messages()` 的返回顺序
  6. * (按 `sequence` 升序)正是判据的一半——用假 store 就把被测的那个性质自己假设掉了。
  7. */
  8. import { mkdtemp, rm } from "node:fs/promises";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { describe, expect, it } from "vitest";
  12. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  13. import {
  14. createMessageId,
  15. createPartId,
  16. type MessageId,
  17. type MessagePart,
  18. type SessionId,
  19. } from "@zcode/contracts";
  20. import { WorkflowError } from "@zcode/dynamic-workflow";
  21. import {
  22. seedActorTranscript,
  23. type ActorTranscriptStore,
  24. } from "../src/app/workflow-actor-transcript.js";
  25. const SOURCE = "sess-source" as SessionId;
  26. const TARGET = "sess-target" as SessionId;
  27. const CWD = "/tmp/dwf-seed";
  28. type Store = ActorTranscriptStore & {
  29. close(): void;
  30. createSession(input: unknown): Promise<unknown>;
  31. };
  32. /**
  33. * 种子副本的 id 规则,与 workflow-actor-transcript.ts 的 `seededMessageId` 必须逐字一致——
  34. * 这正是「这条消息是不是我抄进来的」的判据,所以连 `createMessageId` 的前缀都得走同一个函数。
  35. */
  36. function seedId(sessionId: SessionId, index: number): MessageId {
  37. return createMessageId(`${sessionId}-seed-${index}`);
  38. }
  39. async function saveMessage(
  40. store: ActorTranscriptStore,
  41. input: {
  42. id: MessageId;
  43. sessionId: SessionId;
  44. text: string;
  45. at: number;
  46. /** 缺省是一个与消息 id 绑定的 part id;种子前缀要用生产那一套(见 {@link fillSeeded})。 */
  47. partId?: MessagePart["id"];
  48. },
  49. ): Promise<void> {
  50. await store.saveMessage({
  51. id: input.id,
  52. sessionID: input.sessionId,
  53. role: "user",
  54. time: { created: input.at },
  55. path: { cwd: CWD, root: CWD },
  56. } as never);
  57. await store.savePart({
  58. id: input.partId ?? (`${input.id}_text` as MessagePart["id"]),
  59. sessionID: input.sessionId,
  60. messageID: input.id,
  61. type: "text",
  62. text: input.text,
  63. time: { start: input.at, end: input.at },
  64. } as never);
  65. }
  66. /** 源会话:`count` 条可辨认的消息。 */
  67. async function fillSource(store: ActorTranscriptStore, count: number): Promise<void> {
  68. for (let index = 0; index < count; index++) {
  69. await saveMessage(store, {
  70. id: `src-${index}` as MessageId,
  71. sessionId: SOURCE,
  72. text: `source ${index}`,
  73. at: index + 1,
  74. });
  75. }
  76. }
  77. /**
  78. * 目标会话:`count` 条**种子 id** 的消息(一截复制出来的前缀)。
  79. *
  80. * 消息与 part 的 id 都按生产那一套铸(`seededMessageId` / `seededPartId`),因为重抄靠的正是
  81. * 「同 id upsert」:part id 若不同,重抄就会在同一条消息下多长出一个 part 而不是覆盖它。
  82. */
  83. async function fillSeeded(store: ActorTranscriptStore, count: number): Promise<void> {
  84. for (let index = 0; index < count; index++) {
  85. await saveMessage(store, {
  86. id: seedId(TARGET, index),
  87. sessionId: TARGET,
  88. text: `seeded ${index}`,
  89. at: index + 1,
  90. partId: createPartId(`${TARGET}-seed-${index}-0`),
  91. });
  92. }
  93. }
  94. async function textsOf(store: ActorTranscriptStore, sessionId: SessionId): Promise<string[]> {
  95. const messages = await store.messages({ sessionID: sessionId });
  96. return messages.map((message) =>
  97. message.parts.map((part) => (part.type === "text" ? part.text : "")).join(""),
  98. );
  99. }
  100. /** `message.session_id` 对 `session(id)` 有 FK,所以两个会话行都得先落。 */
  101. async function createSessionRow(store: Store, sessionId: SessionId): Promise<void> {
  102. await store.createSession({
  103. id: sessionId,
  104. projectID: "project_dwf_seed",
  105. slug: `slug-${sessionId}`,
  106. directory: CWD,
  107. path: CWD,
  108. title: `session ${sessionId}`,
  109. version: "test-version",
  110. time: { created: 1, updated: 1 },
  111. } as never);
  112. }
  113. async function withStore(body: (store: Store) => Promise<void>): Promise<void> {
  114. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-seed-"));
  115. const store = createSqliteSessionStore({
  116. dbPath: join(tempRoot, "session.sqlite"),
  117. }) as unknown as Store;
  118. try {
  119. await createSessionRow(store, SOURCE);
  120. await createSessionRow(store, TARGET);
  121. await body(store);
  122. } finally {
  123. store.close();
  124. await rm(tempRoot, { force: true, recursive: true });
  125. }
  126. }
  127. describe("seedActorTranscript — 跳过规则", () => {
  128. it("目标已有 ≥ messageCount 条 → 整段跳过(崩溃后 resume 的常态)", async () => {
  129. await withStore(async (store) => {
  130. await fillSource(store, 4);
  131. await fillSeeded(store, 3);
  132. const copied = await seedActorTranscript({
  133. seed: { sourceSessionId: SOURCE, messageCount: 3 },
  134. store,
  135. targetSessionId: TARGET,
  136. });
  137. expect(copied).toBeUndefined();
  138. expect(await textsOf(store, TARGET)).toEqual(["seeded 0", "seeded 1", "seeded 2"]);
  139. });
  140. });
  141. // 复制中途崩溃留下的半截前缀:全是种子 id,所以补齐它是安全的。
  142. it("目标只有 k < N 条种子消息 → 补齐到 N", async () => {
  143. await withStore(async (store) => {
  144. await fillSource(store, 4);
  145. await fillSeeded(store, 1);
  146. const copied = await seedActorTranscript({
  147. seed: { sourceSessionId: SOURCE, messageCount: 3 },
  148. store,
  149. targetSessionId: TARGET,
  150. });
  151. expect(copied).toBe(3);
  152. // 前一条被同 id upsert 成源的内容,后两条是新抄的;顺序与源一致。
  153. expect(await textsOf(store, TARGET)).toEqual(["source 0", "source 1", "source 2"]);
  154. });
  155. });
  156. // 同一条 ask 的更晚快照:目标仍只有种子消息,所以延长到 M 是安全的。
  157. it("目标是 N 条种子消息、边界长到 M > N → 延长到 M", async () => {
  158. await withStore(async (store) => {
  159. await fillSource(store, 5);
  160. await fillSeeded(store, 2);
  161. const copied = await seedActorTranscript({
  162. seed: { sourceSessionId: SOURCE, messageCount: 4 },
  163. store,
  164. targetSessionId: TARGET,
  165. });
  166. expect(copied).toBe(4);
  167. expect(await textsOf(store, TARGET)).toEqual([
  168. "source 0",
  169. "source 1",
  170. "source 2",
  171. "source 3",
  172. ]);
  173. });
  174. });
  175. /**
  176. * 本轮的核心防线:目标已经有自己的 live 消息,而重建出来的边界比目标总条数还大。
  177. *
  178. * 老规则会重抄 0..M-1——前面那些是对种子 id 的 upsert,而 N..M-1 是新 id,于是前驱的消息被
  179. * 追加到本会话自己的历史**之后**(`sequence` 在 insert 时取 max+1)。那是一段前后颠倒、且
  180. * 不属于这个子代理的上文,而且悄无声息。
  181. */
  182. it("目标已有自己的 live 消息 → 一个字节都不写,哪怕总条数不足 messageCount", async () => {
  183. await withStore(async (store) => {
  184. await fillSource(store, 9);
  185. await fillSeeded(store, 2);
  186. // 本会话自己跑出来的两条:id 不是种子 id。
  187. await saveMessage(store, {
  188. id: "live-0" as MessageId,
  189. sessionId: TARGET,
  190. text: "live 0",
  191. at: 10,
  192. });
  193. await saveMessage(store, {
  194. id: "live-1" as MessageId,
  195. sessionId: TARGET,
  196. text: "live 1",
  197. at: 11,
  198. });
  199. const before = await textsOf(store, TARGET);
  200. const copied = await seedActorTranscript({
  201. seed: { sourceSessionId: SOURCE, messageCount: 7 },
  202. store,
  203. targetSessionId: TARGET,
  204. });
  205. expect(copied).toBeUndefined();
  206. expect(await textsOf(store, TARGET)).toEqual(before);
  207. // 尤其是:没有任何一条前驱消息被追加到 live 消息之后。
  208. expect(await textsOf(store, TARGET)).toEqual(["seeded 0", "seeded 1", "live 0", "live 1"]);
  209. });
  210. });
  211. it("空目标照常复制", async () => {
  212. await withStore(async (store) => {
  213. await fillSource(store, 3);
  214. const copied = await seedActorTranscript({
  215. seed: { sourceSessionId: SOURCE, messageCount: 2 },
  216. store,
  217. targetSessionId: TARGET,
  218. });
  219. expect(copied).toBe(2);
  220. expect(await textsOf(store, TARGET)).toEqual(["source 0", "source 1"]);
  221. });
  222. });
  223. // 源短于边界是 corruption 级:service 侧的门本该先把这种候选弃掉(见那边的 countSource)。
  224. it("源会话短于边界 → DriverError", async () => {
  225. await withStore(async (store) => {
  226. await fillSource(store, 2);
  227. await expect(
  228. seedActorTranscript({
  229. seed: { sourceSessionId: SOURCE, messageCount: 5 },
  230. store,
  231. targetSessionId: TARGET,
  232. }),
  233. ).rejects.toThrow(WorkflowError);
  234. expect(await textsOf(store, TARGET)).toEqual([]);
  235. });
  236. });
  237. it("跳过写进已开跑会话时记一条 warn(边界长大的唯一可见处)", async () => {
  238. await withStore(async (store) => {
  239. await fillSource(store, 9);
  240. await fillSeeded(store, 1);
  241. await saveMessage(store, {
  242. id: "live-0" as MessageId,
  243. sessionId: TARGET,
  244. text: "live 0",
  245. at: 10,
  246. });
  247. const warnings: { message: string; context?: Record<string, unknown> }[] = [];
  248. await seedActorTranscript({
  249. logger: {
  250. warn: (message: string, context?: Record<string, unknown>) =>
  251. warnings.push({ message, context }),
  252. } as never,
  253. seed: { sourceSessionId: SOURCE, messageCount: 7 },
  254. store,
  255. targetSessionId: TARGET,
  256. });
  257. expect(warnings).toHaveLength(1);
  258. expect(warnings[0]?.context).toMatchObject({
  259. event: "dynamic_workflow.actor.seed_skipped_live_session",
  260. existingMessageCount: 2,
  261. messageCount: 7,
  262. });
  263. });
  264. });
  265. });