v4ResyncNotOwnedEvictionRace.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // fault.subscription.notOwned 线上竞态(zcode-logs-full-20260730-204321 三起事件)的机制层还原
  2. // 与修复验证。
  3. //
  4. // 竞态时序(renderer ⇄ host 为异步链路,远程 SSH workspace 下窗口达数百 ms):
  5. //
  6. // renderer(store/transport) host(connectionScope) CLI(base)
  7. // ────────────────────────── ───────────────────── ─────────
  8. // connect() → subscribe ────────────▶ remember(S1) ◀────────────────── ACK S1
  9. // [S1 live]
  10. // connect() 换代重订阅 ──subscribe(S2) 在途──▶ …
  11. // S1 online 帧断档
  12. // → resync(S1) 通过本地
  13. // ownership 检查,RPC 在途 ─────▶ …
  14. // sendCommand ──────────────────────▶ 校验通过 ─────────────────────▶ 成功
  15. // remember(S2):同 ownershipKey
  16. // 静默驱逐 S1(不发 unsubscribe、
  17. // 无 runtime restart)◀────────── ACK S2
  18. // [S2 live]
  19. // 迟到的 resync(S1) 抵达 ───────────▶ findBySubscription 找不到 S1
  20. // → 拒绝 fault.subscription.notOwned
  21. //
  22. // 修复前 store 会把这次迟到失败写成 status="error" 且无自动重连(会话永久卡死,需手动重连)。
  23. // 修复后的正确行为分两层,对应本文件的两个正向用例:
  24. // 1. connect() 换代成功时丢弃 await 窗口内创建的旧订阅 recovery——迟到的 notOwned
  25. // 属于已换代丢弃的恢复流,静默忽略,S2 保持 live;
  26. // 2. 若 notOwned 命中的是"仍属当前订阅"的 recovery(如错位 unsubscribe 造成的
  27. // ownership 分歧),store 携当前水位 fresh subscribe 自愈,不落 error。
  28. import { Emitter } from "@zcode/rpc";
  29. import type { LocalTtftFacts } from "@zcode/shared";
  30. import type {
  31. ConversationTopicFrame,
  32. ConversationTopicWireFrame,
  33. } from "@zcode/shared/zcode-protocol-v4";
  34. import {
  35. createZCodeAgentConnectionScope,
  36. readTrustedZCodeAgentV4Connection,
  37. type IZCodeAgentService,
  38. } from "@zcode/services";
  39. import { describe, expect, it, vi } from "vitest";
  40. import { createAgentConversationTransport } from "@/v4/agentConversationTransport.js";
  41. import { ConversationProjectionStore } from "@/v4/conversationProjectionStore.js";
  42. import { createCommandEnvelope } from "@/v4/commandFactory.js";
  43. const TOPIC = "conversation/s1";
  44. const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
  45. // ── CLI base mock:只提供 conversation 面所需的最小行为 ──
  46. function setupBase() {
  47. const conversationFrames = new Emitter<ConversationTopicWireFrame>();
  48. const localTtftFacts = new Emitter<LocalTtftFacts>();
  49. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  50. const nextSerialByConnection = new Map<string, number>();
  51. const nextId = (params: unknown) => {
  52. const connection = readTrustedZCodeAgentV4Connection(params);
  53. if (!connection) throw new Error("missing trusted connection");
  54. const serial = (nextSerialByConnection.get(connection.connectionId) ?? 0) + 1;
  55. nextSerialByConnection.set(connection.connectionId, serial);
  56. return `sub-${connection.connectionId}-${serial}`;
  57. };
  58. const mocks = {
  59. helloConversationV4: vi.fn(),
  60. initializeConversationV4: vi.fn(),
  61. subscribeConversationV4: vi.fn(async (params: unknown) => ({
  62. ack: {
  63. subscriptionId: nextId(params),
  64. mode: "snapshot" as const,
  65. logEpoch: "epoch-1",
  66. },
  67. })),
  68. unsubscribeConversationV4: vi.fn(async () => {}),
  69. resyncConversationV4: vi.fn(async (params: { subscriptionId: string }) => ({
  70. ack: {
  71. subscriptionId: params.subscriptionId,
  72. mode: "resume" as const,
  73. logEpoch: "epoch-1",
  74. },
  75. })),
  76. sendConversationCommandV4: vi.fn(async (params: { envelope: { commandId: string } }) => ({
  77. commandId: params.envelope.commandId,
  78. status: "accepted" as const,
  79. revisionAtDecision: 1,
  80. })),
  81. onDynamicConversationFrame: vi.fn(() => conversationFrames.event),
  82. // transport.onFrame 会顺带挂载本地 TTFT 检查点 emitter(desktop-continuous 本地
  83. // workspace 才有),base 必须提供该动态 Event,否则 connectionScope 转发时直接抛错。
  84. onDynamicLocalTtftFacts: vi.fn(() => localTtftFacts.event),
  85. onAgentRuntimeRestarted: vi.fn((listener: (event: { workspaceKey: string }) => void) =>
  86. runtimeRestarts.event(listener),
  87. ),
  88. setConnectionFlowStateV4: vi.fn(async () => {}),
  89. };
  90. return {
  91. base: mocks as unknown as IZCodeAgentService,
  92. mocks,
  93. conversationFrames,
  94. };
  95. }
  96. // ── RPC 延迟闸门:模拟 renderer→host 链路上的在途请求(远程 SSH 下真实存在的时延)──
  97. function createRpcGate(service: IZCodeAgentService) {
  98. const holding = new Set<string>();
  99. const held = new Map<string, Array<() => void>>();
  100. const proxy = new Proxy(service as unknown as Record<string, unknown>, {
  101. get(target, property, receiver) {
  102. const value = Reflect.get(target, property, receiver);
  103. if (typeof value !== "function") return value;
  104. const method = String(property);
  105. return (...args: unknown[]) => {
  106. if (!holding.has(method)) return (value as (...a: unknown[]) => unknown)(...args);
  107. return new Promise((resolve, reject) => {
  108. const queue = held.get(method) ?? [];
  109. queue.push(() => {
  110. Promise.resolve()
  111. .then(() => (value as (...a: unknown[]) => unknown)(...args))
  112. .then(resolve, reject);
  113. });
  114. held.set(method, queue);
  115. });
  116. };
  117. },
  118. }) as unknown as IZCodeAgentService;
  119. return {
  120. service: proxy,
  121. hold(method: string) {
  122. holding.add(method);
  123. },
  124. heldCount(method: string) {
  125. return held.get(method)?.length ?? 0;
  126. },
  127. async release(method: string) {
  128. holding.delete(method);
  129. const queue = held.get(method) ?? [];
  130. held.delete(method);
  131. for (const run of queue) run();
  132. await flush();
  133. },
  134. };
  135. }
  136. function onlineDeltasWire(
  137. subscriptionId: string,
  138. ordinal: number,
  139. fromSeq: number,
  140. toSeq: number,
  141. ): ConversationTopicWireFrame {
  142. const frame: ConversationTopicFrame = {
  143. topic: TOPIC,
  144. subscriptionId,
  145. fromSeq,
  146. toSeq,
  147. sentAt: 1,
  148. payload: { kind: "deltas", deltas: [] },
  149. };
  150. return {
  151. wireVersion: 3,
  152. kind: "complete",
  153. deliveryKind: "online",
  154. logicalFrameId: `logical-${subscriptionId}-${ordinal}`,
  155. logicalFrameOrdinal: ordinal,
  156. topic: TOPIC,
  157. subscriptionId,
  158. frame,
  159. };
  160. }
  161. describe("v4 resync notOwned eviction race(真实 store + transport + connectionScope)", () => {
  162. it("换代 subscribe ACK 静默驱逐旧 ownership 后,迟到 resync 的 notOwned 被静默忽略,S2 保持 live", async () => {
  163. const { base, mocks, conversationFrames } = setupBase();
  164. const scope = createZCodeAgentConnectionScope(base, {
  165. connectionId: "conn-1",
  166. clientMode: "desktop-continuous",
  167. });
  168. const gate = createRpcGate(scope.service);
  169. const transport = createAgentConversationTransport(gate.service, {
  170. workspacePath: "/repo",
  171. });
  172. const store = new ConversationProjectionStore(TOPIC, transport);
  173. const offFrame = transport.onFrame((frame, context) => store.handleFrame(frame, context));
  174. // 1) 首连成功:S1 上线(initial 帧尚未到达,appliedBase=false——与线上远程链路一致)。
  175. await store.connect();
  176. expect(store.getState().status).toBe("live");
  177. expect(store.getState().subscriptionId).toBe("sub-conn-1-1");
  178. // 2) UI 换代重订阅(真实触发点:retry()、resume initial 断档强 snapshot、
  179. // initialFrameStagingOverflow 自动重试等),subscribe(S2) 在 renderer→host 链路上在途。
  180. gate.hold("subscribeConversationV4");
  181. const reconnect = store.connect();
  182. await flush();
  183. expect(gate.heldCount("subscribeConversationV4")).toBe(1);
  184. // 3) 竞态窗口内 S1 收到 online delta(initial 缺失 → same-sub recovery):
  185. // resync(S1) 已通过 transport 本地 ownership 检查,RPC 同样在途。
  186. gate.hold("resyncConversationV4");
  187. conversationFrames.fire(onlineDeltasWire("sub-conn-1-1", 1, 7, 8));
  188. await flush();
  189. expect(gate.heldCount("resyncConversationV4")).toBe(1);
  190. // 3.5) 同窗口 command 照常成功——对应线上日志"resync 失败前 sendCommand 正常",
  191. // 证明连接与握手都健康,排除断连/重启因素。
  192. const ack = await transport.sendCommand(
  193. createCommandEnvelope({ type: "sendText", payload: { text: "hi" }, sessionId: "s1" }),
  194. );
  195. expect(ack.status).toBe("accepted");
  196. // 4) subscribe(S2) ACK 先抵达 host:remember() 以同 ownershipKey
  197. // (conversation, workspace, topic, connectionId) 静默驱逐 S1——
  198. // 不向 CLI 发 unsubscribe,也没有 runtime restart。
  199. await gate.release("subscribeConversationV4");
  200. await reconnect;
  201. expect(store.getState().status).toBe("live");
  202. expect(store.getState().subscriptionId).toBe("sub-conn-1-2");
  203. expect(mocks.unsubscribeConversationV4).not.toHaveBeenCalled();
  204. // 5) 迟到的 resync(S1) 此刻才抵达 host scope → fault.subscription.notOwned。
  205. await gate.release("resyncConversationV4");
  206. await flush();
  207. // 修复后形态:scope 仍然拒绝(请求未到 CLI),但 store 在换代成功时已丢弃 S1 的
  208. // recovery,迟到失败被静默忽略——S2 保持 live,不落 error,也不触发多余的重订阅。
  209. expect(mocks.resyncConversationV4).not.toHaveBeenCalled();
  210. expect(store.getState().status).toBe("live");
  211. expect(store.getState().subscriptionId).toBe("sub-conn-1-2");
  212. expect(store.getState().lastError).toBeNull();
  213. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  214. offFrame();
  215. });
  216. it("错位 unsubscribe 造成 ownership 分歧时,resync notOwned 自动携水位重订阅自愈", async () => {
  217. const { base, mocks, conversationFrames } = setupBase();
  218. const scope = createZCodeAgentConnectionScope(base, {
  219. connectionId: "conn-3",
  220. clientMode: "desktop-continuous",
  221. });
  222. const gate = createRpcGate(scope.service);
  223. const transport = createAgentConversationTransport(gate.service, {
  224. workspacePath: "/repo",
  225. });
  226. const store = new ConversationProjectionStore(TOPIC, transport);
  227. const offFrame = transport.onFrame((frame, context) => store.handleFrame(frame, context));
  228. await store.connect();
  229. expect(store.getState().subscriptionId).toBe("sub-conn-3-1");
  230. // 断档触发 same-sub recovery:resync(S1) 在 renderer→host 链路上在途。
  231. gate.hold("resyncConversationV4");
  232. conversationFrames.fire(onlineDeltasWire("sub-conn-3-1", 1, 7, 8));
  233. await flush();
  234. expect(gate.heldCount("resyncConversationV4")).toBe(1);
  235. // 错位退订:另一个持有同连接的调用方(重复挂载的 data layer / 旧视图实例)直接向
  236. // scope 退订 S1。transport 本地 map 不知情——线上日志"unsubscribe → resync notOwned"
  237. // 序列即此形态。
  238. await scope.service.unsubscribeConversationV4({
  239. workspacePath: "/repo",
  240. subscriptionId: "sub-conn-3-1",
  241. });
  242. // 迟到的 resync(S1) 抵达 → notOwned。修复后 store 不落 error,而是携当前水位
  243. // fresh subscribe(由服务端裁决 resume/snapshot)完成自愈。
  244. await gate.release("resyncConversationV4");
  245. await vi.waitFor(() => {
  246. expect(store.getState().subscriptionId).toBe("sub-conn-3-2");
  247. });
  248. expect(store.getState().status).toBe("live");
  249. expect(store.getState().lastError).toBeNull();
  250. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  251. offFrame();
  252. });
  253. it("对照:resync(S1) 先于 subscribe(S2) ACK 抵达 host 时不触发 notOwned", async () => {
  254. const { base, mocks, conversationFrames } = setupBase();
  255. const scope = createZCodeAgentConnectionScope(base, {
  256. connectionId: "conn-2",
  257. clientMode: "desktop-continuous",
  258. });
  259. const gate = createRpcGate(scope.service);
  260. const transport = createAgentConversationTransport(gate.service, {
  261. workspacePath: "/repo",
  262. });
  263. const store = new ConversationProjectionStore(TOPIC, transport);
  264. const offFrame = transport.onFrame((frame, context) => store.handleFrame(frame, context));
  265. await store.connect();
  266. expect(store.getState().subscriptionId).toBe("sub-conn-2-1");
  267. gate.hold("subscribeConversationV4");
  268. const reconnect = store.connect();
  269. await flush();
  270. gate.hold("resyncConversationV4");
  271. conversationFrames.fire(onlineDeltasWire("sub-conn-2-1", 1, 7, 8));
  272. await flush();
  273. expect(gate.heldCount("resyncConversationV4")).toBe(1);
  274. // 唯一差异:到达顺序对调——resync(S1) 先落地,此刻 scope 仍持有 S1 ownership。
  275. await gate.release("resyncConversationV4");
  276. expect(mocks.resyncConversationV4).toHaveBeenCalledTimes(1);
  277. expect(store.getState().status).not.toBe("error");
  278. await gate.release("subscribeConversationV4");
  279. await reconnect;
  280. expect(store.getState().status).toBe("live");
  281. expect(store.getState().subscriptionId).toBe("sub-conn-2-2");
  282. expect(store.getState().lastError).toBeNull();
  283. offFrame();
  284. });
  285. });