session-creation-retries.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import { verifySessionCreationIdentityMigration } from "#e2e/helpers/session-creation-identity-migration";
  2. import { fork } from "node:child_process";
  3. import assert from "node:assert/strict";
  4. import { createHash, randomUUID } from "node:crypto";
  5. import { join } from "node:path";
  6. import { DatabaseSync } from "node:sqlite";
  7. import { BUILTIN_MODEL_PROVIDER_IDS, resolveWorkspaceKey } from "@zcode/shared";
  8. import type { CommandAck, CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  9. import { projectStorage } from "../../../../services/src/project-storage/index.js";
  10. import { createWorkerSelectionIntegration } from "#e2e/helpers/worker-selection-integration";
  11. /** 使用真实 Host/stdio CLI;销毁全部 Worker、重开组织库后才重放原始信封。 */
  12. export async function verifySessionCreationRetries() {
  13. let host = await createWorkerSelectionIntegration("session-id-retry-host");
  14. const workspacePath = host.workspacePath;
  15. const makeCommand = (label: string): CommandEnvelope => ({
  16. commandId: randomUUID(),
  17. clientId: "e2e-old-client",
  18. sessionId: null,
  19. type: "createSession",
  20. issuedAt: Date.now(),
  21. payload: {
  22. workspaceId: workspacePath,
  23. firstInput: {
  24. text: `E2E_SID_RETRY_${label}`,
  25. modelSelection: {
  26. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  27. modelId: "GLM-5.3-Flash",
  28. options: { reasoningLevel: "high" },
  29. },
  30. },
  31. },
  32. });
  33. const send = (envelope: CommandEnvelope) =>
  34. host.agent.sendConversationCommandV4({
  35. workspacePath,
  36. projectId: null,
  37. envelope: structuredClone(envelope),
  38. });
  39. const idOf = (ack: CommandAck): string => {
  40. assert.ok(["accepted", "duplicate"].includes(ack.status), JSON.stringify(ack));
  41. assert.equal(ack.result?.type, "createSession");
  42. return (ack.result as { sessionId: string }).sessionId;
  43. };
  44. const reserve = (command: CommandEnvelope, taskId?: string) =>
  45. host.projects.reserveCreatedTask({
  46. task: { workspacePath, taskId },
  47. projectId: null,
  48. creationCommand: { commandId: command.commandId, clientId: command.clientId },
  49. });
  50. const rows = async () => {
  51. const db = await host.repo.getOrganizationDatabase();
  52. return db.prepare("SELECT * FROM tasks ORDER BY workspace_key,task_id").all();
  53. };
  54. const waitComplete = async (id: string) => {
  55. await browser.waitUntil(
  56. async () => {
  57. const snapshot = await host.agent.readSession({ workspacePath, sessionId: id });
  58. // 正文完成后标题仍会异步落库;等标题事实完成,再冻结用于重放对比的整行快照。
  59. return (
  60. snapshot.session.status === "idle" &&
  61. JSON.stringify(snapshot.messages).includes("E2E_SID_RETRY_OK") &&
  62. cliFacts().sessions.find((row) => row.id === id)?.title_source === "generated"
  63. );
  64. },
  65. { timeout: 60000, timeoutMsg: `重试测试会话未完成 ${id}` },
  66. );
  67. };
  68. const cliFacts = () => {
  69. const db = new DatabaseSync(join(host.home, ".zcode/cli/db/db.sqlite"), { readOnly: true });
  70. try {
  71. return {
  72. sessions: db.prepare("SELECT * FROM session ORDER BY id").all(),
  73. inputs: db.prepare("SELECT * FROM session_input ORDER BY id").all(),
  74. messages: db.prepare("SELECT * FROM message ORDER BY id").all(),
  75. parts: db.prepare("SELECT * FROM part ORDER BY id").all(),
  76. };
  77. } finally {
  78. db.close();
  79. }
  80. };
  81. const restart = async () => {
  82. await host.dispose();
  83. host = await createWorkerSelectionIntegration("session-id-retry-host");
  84. };
  85. try {
  86. const organization = await host.repo.getOrganizationDatabase();
  87. const migrationPath = join(host.home, "migration-check.sqlite");
  88. organization.prepare("VACUUM INTO ?").run(migrationPath);
  89. const migration = new DatabaseSync(migrationPath);
  90. try {
  91. const repository = projectStorage.repository(migration);
  92. for (const taskId of [
  93. "session_0123456789abcdef0123456789abcdef",
  94. "session_12345678-1234-4234-8234-123456789abc",
  95. ]) {
  96. repository.reserveCreatedTask({ task: { workspacePath, taskId }, projectId: null });
  97. }
  98. migration.exec(
  99. "DROP TABLE session_creation_commands; DELETE FROM schema_migration WHERE id='0009_session_creation_commands'",
  100. );
  101. const tables = migration
  102. .prepare(
  103. "SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('schema_migration','session_creation_commands') ORDER BY name",
  104. )
  105. .all();
  106. const snapshot = () =>
  107. tables.map(({ name }) => ({
  108. name,
  109. rows: migration
  110. .prepare(`SELECT * FROM "${String(name).replaceAll('"', '""')}" ORDER BY rowid`)
  111. .all(),
  112. }));
  113. const original = snapshot();
  114. await projectStorage.migrate(migration, { backupDirectories: [host.home] });
  115. assert.deepEqual(snapshot(), original);
  116. assert.equal(
  117. migration.prepare("SELECT count(*) AS n FROM session_creation_commands").get()!.n,
  118. 0,
  119. );
  120. } finally {
  121. migration.close();
  122. }
  123. const identityMigration = await verifySessionCreationIdentityMigration(
  124. join(host.home, "identity-migration.sqlite"),
  125. );
  126. const sequential = makeCommand("SEQUENTIAL");
  127. const id = idOf(await send(sequential));
  128. assert.match(id, /^sess_[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/);
  129. assert.equal(idOf(await send(sequential)), id);
  130. assert.equal((await rows()).length, 1);
  131. await waitComplete(id);
  132. const concurrent = makeCommand("CONCURRENT");
  133. const concurrentIds = await Promise.all(
  134. Array.from({ length: 8 }, async () => idOf(await send(concurrent))),
  135. );
  136. assert.equal(new Set(concurrentIds).size, 1);
  137. assert.equal((await rows()).length, 2);
  138. await waitComplete(concurrentIds[0]!);
  139. // 模拟 3.16:已有旧哈希 ID 和 CLI durable fact,但没有新版分配回执。
  140. const legacy = makeCommand("LEGACY");
  141. const legacyId = `session_${createHash("sha256")
  142. .update(
  143. JSON.stringify([resolveWorkspaceKey({ workspacePath }), legacy.clientId, legacy.commandId]),
  144. )
  145. .digest("hex")
  146. .slice(0, 32)}`;
  147. const legacyExplicit = structuredClone(legacy);
  148. legacyExplicit.payload = { ...(legacyExplicit.payload as object), sessionId: legacyId };
  149. assert.equal(idOf(await send(legacyExplicit)), legacyId);
  150. await waitComplete(legacyId);
  151. const db = await host.repo.getOrganizationDatabase();
  152. db.prepare("DELETE FROM session_creation_commands WHERE command_id=?").run(legacy.commandId);
  153. const before = cliFacts();
  154. // 同一同步调用段取快照,避免正常异步索引同步插入两次观测之间。
  155. const frozenRows = () => db.prepare("SELECT * FROM tasks ORDER BY workspace_key,task_id").all();
  156. const oldRows = frozenRows();
  157. assert.equal(reserve(legacy).taskId, legacyId);
  158. assert.deepEqual(frozenRows(), oldRows);
  159. db.prepare("DELETE FROM session_creation_commands WHERE command_id=?").run(legacy.commandId);
  160. // 接口已预留、尚未投递 CLI 的崩溃窗口。
  161. const reserved = makeCommand("RESERVATION_ONLY");
  162. const reservedId = reserve(reserved).taskId;
  163. await restart();
  164. for (const [command, expected] of [
  165. [sequential, id],
  166. [concurrent, concurrentIds[0]!],
  167. [legacy, legacyId],
  168. ] as const) {
  169. assert.equal(idOf(await send(command)), expected);
  170. }
  171. assert.deepEqual(cliFacts(), before);
  172. // Host 重启会按 CLI 持久事实刷新缓存时间;CLI 原行仍须完全一致,Host 核对身份与组织态。
  173. const ownership = (records: Awaited<ReturnType<typeof rows>>) =>
  174. records.map((row) =>
  175. Object.fromEntries(
  176. [
  177. "workspace_key",
  178. "workspace_path",
  179. "workspace_identity",
  180. "task_id",
  181. "host_id",
  182. "root_path",
  183. "project_id",
  184. "execution_directories",
  185. "sort_order",
  186. "pinned",
  187. "archived",
  188. "deleted",
  189. "handoff_pending",
  190. ].map((key) => [key, row[key]]),
  191. ),
  192. );
  193. assert.deepEqual(
  194. ownership((await rows()).filter((row) => row.task_id !== reservedId)),
  195. ownership(oldRows),
  196. );
  197. assert.equal(idOf(await send(reserved)), reservedId);
  198. await waitComplete(reservedId);
  199. const after = cliFacts();
  200. assert.equal(after.sessions.length, 4);
  201. assert.equal(after.inputs.length, 4);
  202. await restart();
  203. assert.equal(idOf(await send(reserved)), reservedId);
  204. assert.deepEqual(cliFacts(), after);
  205. const empty = makeCommand("EMPTY_DRAFT");
  206. empty.payload = { workspaceId: workspacePath };
  207. const emptyId = idOf(await send(empty));
  208. assert.equal(idOf(await send(empty)), emptyId);
  209. await restart();
  210. assert.equal(idOf(await send(empty)), emptyId);
  211. assert.deepEqual(cliFacts(), after);
  212. // 独立 SQLite 连接重入、命令隔离和失败原子性;不制造模型请求。
  213. const database = await host.repo.getOrganizationDatabase();
  214. const dbPath = database.prepare("PRAGMA database_list").get()!.file as string;
  215. const processCommand = makeCommand("PROCESS_CONCURRENT");
  216. const input = { task: { workspacePath }, projectId: null, creationCommand: processCommand };
  217. const spawnReservation = () => {
  218. const child = fork(
  219. new URL("./session-creation-reservation-process.ts", import.meta.url),
  220. [JSON.stringify({ databasePath: dbPath, input })],
  221. {
  222. execArgv: ["--import", import.meta.resolve("tsx")],
  223. stdio: ["ignore", "inherit", "inherit", "ipc"],
  224. },
  225. );
  226. const result = new Promise<string>((resolve, reject) => {
  227. let taskId: string | undefined;
  228. child.on("message", (message: { taskId?: string; error?: string }) => {
  229. if (message.taskId) taskId = message.taskId;
  230. if (message.error) reject(new Error(message.error));
  231. });
  232. child.once("error", reject);
  233. child.once("exit", (code) =>
  234. code === 0 && taskId ? resolve(taskId) : reject(new Error(`预留进程退出 ${code}`)),
  235. );
  236. });
  237. const ready = new Promise<void>((resolve, reject) => {
  238. child.once("message", () => resolve());
  239. child.once("error", reject);
  240. child.once("exit", (code) => reject(new Error(`预留进程提前退出 ${code}`)));
  241. });
  242. return { child, ready, result };
  243. };
  244. const processes = Array.from({ length: 8 }, spawnReservation);
  245. let processId: string;
  246. try {
  247. const results = Promise.all(processes.map((p) => p.result));
  248. await Promise.all(processes.map((p) => p.ready));
  249. processes.forEach((p) => p.child.send("reserve"));
  250. const ids = await results;
  251. assert.equal(new Set(ids).size, 1);
  252. processId = ids[0]!;
  253. } finally {
  254. processes.forEach((p) => p.child.kill());
  255. }
  256. // 新进程重放原始命令,排除 Host 模块缓存掩盖丢失的持久化。
  257. const replayProcess = spawnReservation();
  258. try {
  259. await replayProcess.ready;
  260. replayProcess.child.send("reserve");
  261. assert.equal(await replayProcess.result, processId);
  262. } finally {
  263. replayProcess.child.kill();
  264. }
  265. const second = new DatabaseSync(dbPath);
  266. try {
  267. const other = projectStorage.repository(second);
  268. assert.equal(
  269. other.reserveCreatedTask({
  270. task: { workspacePath },
  271. projectId: null,
  272. creationCommand: sequential,
  273. }).taskId,
  274. id,
  275. );
  276. for (const command of [
  277. sequential,
  278. { ...sequential, clientId: "other-client" },
  279. makeCommand("ISOLATED"),
  280. ]) {
  281. const result = reserve(command).taskId;
  282. assert.equal(
  283. result === id,
  284. command.clientId === sequential.clientId && command.commandId === sequential.commandId,
  285. );
  286. }
  287. const separate = other.reserveCreatedTask({
  288. task: { workspacePath: join(workspacePath, "other") },
  289. projectId: null,
  290. creationCommand: sequential,
  291. });
  292. assert.notEqual(separate.taskId, id);
  293. assert.throws(() => reserve(sequential, `sess_${randomUUID()}`), /creation-id-conflict/);
  294. const failed = makeCommand("INVALID_PROJECT");
  295. const count = database.prepare("SELECT count(*) AS n FROM session_creation_commands").get();
  296. assert.throws(() =>
  297. other.reserveCreatedTask({
  298. task: { workspacePath },
  299. projectId: "missing-project",
  300. creationCommand: failed,
  301. }),
  302. );
  303. assert.deepEqual(
  304. database.prepare("SELECT count(*) AS n FROM session_creation_commands").get(),
  305. count,
  306. );
  307. const deleted = makeCommand("PURGED");
  308. const deletedId = reserve(deleted).taskId;
  309. database.prepare("DELETE FROM tasks WHERE task_id=?").run(deletedId);
  310. assert.throws(() => reserve(deleted), /creation-task-missing/);
  311. assert.equal(
  312. database.prepare("SELECT task_id FROM tasks WHERE task_id=?").get(deletedId),
  313. undefined,
  314. );
  315. } finally {
  316. second.close();
  317. }
  318. return {
  319. id,
  320. concurrentId: concurrentIds[0],
  321. legacyId,
  322. reservedId,
  323. concurrentRequests: 8,
  324. concurrentProcesses: 8,
  325. processRestartReplay: true,
  326. restarts: 3,
  327. emptyDraftReplay: true,
  328. cliSessions: after.sessions.length,
  329. cliInputs: after.inputs.length,
  330. legacyAllocationRowUnchanged: true,
  331. cliReplayRowsUnchanged: true,
  332. hostOwnershipUnchanged: true,
  333. migrationOldTablesUnchanged: true,
  334. identityMigration,
  335. };
  336. } finally {
  337. await host.dispose();
  338. }
  339. }