conversation-telemetry-identity.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import { describe, expect, it } from "vitest";
  2. import { z } from "zod";
  3. import {
  4. SessionEventType,
  5. ModelErrorCode,
  6. type ModelNetworkStatusEvent,
  7. type SessionEvent,
  8. } from "@zcode/contracts";
  9. import { uuidv7 } from "@zcode/shared";
  10. import { ConversationTelemetryFactNormalizer } from "../src/zcode-protocol-v4/conversation-telemetry-facts.js";
  11. import {
  12. TestAiSdkModelAdapter,
  13. TestProviderConfigFixture,
  14. } from "../../adapters/tests/test-provider-config.js";
  15. import {
  16. executeAdapterGenerateText,
  17. executeAdapterStreamText,
  18. } from "../../adapters/tests/test-adapter-model.js";
  19. function event(type: SessionEvent["type"], payload: unknown, seq: number): SessionEvent {
  20. return {
  21. id: `event-${seq}`,
  22. sessionId: "parent",
  23. turnId: "turn",
  24. traceId: "trace",
  25. sequenceNumber: seq,
  26. timestamp: new Date(),
  27. type,
  28. payload,
  29. } as SessionEvent;
  30. }
  31. describe("main turn telemetry identity", () => {
  32. it("projects admitted mobile origin without copying prompt or arbitrary metadata", () => {
  33. const normalizer = new ConversationTelemetryFactNormalizer();
  34. const started = normalizer.normalize(
  35. "parent",
  36. event(
  37. SessionEventType.TurnStarted,
  38. {
  39. turnNumber: 1,
  40. input: "private prompt",
  41. inputId: "command",
  42. intent: { inputOrigin: "mobile" },
  43. },
  44. 1,
  45. ),
  46. { modelName: "model", modelProvider: "provider" },
  47. );
  48. expect(started).toMatchObject({
  49. inputOrigin: "mobile",
  50. sourceCommandId: "command",
  51. modelName: "model",
  52. modelProvider: "provider",
  53. });
  54. expect(JSON.stringify(started)).not.toContain("private prompt");
  55. });
  56. it.each([undefined, "background_task"])("keeps inputId through %s turn facts", (inputSource) => {
  57. const normalizer = new ConversationTelemetryFactNormalizer();
  58. const inputId = uuidv7();
  59. expect(
  60. normalizer.normalize(
  61. "parent",
  62. event(
  63. SessionEventType.TurnStarted,
  64. {
  65. turnNumber: 1,
  66. input: "prompt",
  67. inputId,
  68. inputSource,
  69. messageId: "msg_persisted",
  70. },
  71. 1,
  72. ),
  73. ),
  74. ).toMatchObject({ sourceCommandId: inputId, kind: "turn.started" });
  75. expect(
  76. normalizer.normalize(
  77. "parent",
  78. event(
  79. SessionEventType.TurnComplete,
  80. {
  81. turnNumber: 1,
  82. result: { type: "complete" },
  83. duration: 10,
  84. },
  85. 2,
  86. ),
  87. ),
  88. ).toMatchObject({ sourceCommandId: inputId, kind: "turn.terminal" });
  89. });
  90. it("does not substitute a persisted message ID for a missing input ID", () => {
  91. const normalizer = new ConversationTelemetryFactNormalizer();
  92. const fact = normalizer.normalize(
  93. "parent",
  94. event(
  95. SessionEventType.TurnStarted,
  96. {
  97. turnNumber: 1,
  98. input: "notice",
  99. inputSource: "background_task",
  100. messageId: "msg_persisted",
  101. },
  102. 1,
  103. ),
  104. );
  105. expect(fact).not.toHaveProperty("sourceCommandId");
  106. });
  107. });
  108. // 必须把真实 Adapter 的网络终态交给真实 normalizer,手工构造 failed 会掩盖完成身份入队回归。
  109. describe.each(["stream", "generate"] as const)("%s empty context recovery identity", (mode) => {
  110. it.each(["success", "failed", "cancelled"])(
  111. "keeps retry and next-turn identity after %s compact",
  112. async (outcome) => {
  113. const normalizer = new ConversationTelemetryFactNormalizer();
  114. let seq = 0;
  115. let turnId = "turn-1";
  116. const publish = (type: SessionEvent["type"], payload: unknown) =>
  117. normalizer.normalize("parent", { ...event(type, payload, ++seq), turnId });
  118. async function request(
  119. id: string,
  120. totalTokens: number,
  121. querySource = "main_turn",
  122. overflow = false,
  123. ) {
  124. const statuses: ModelNetworkStatusEvent[] = [];
  125. const usage = { inputTokens: totalTokens - 5, outputTokens: 5, totalTokens };
  126. const completion = {
  127. finishReason: overflow ? "length" : "stop",
  128. rawFinishReason: overflow ? "model_context_window_exceeded" : "stop",
  129. };
  130. const providerId = `provider-${id}`;
  131. const modelId = `model-${id}`;
  132. const adapter = new TestAiSdkModelAdapter({
  133. registry: new TestProviderConfigFixture({
  134. providers: {
  135. [providerId]: { kind: "custom", createLanguageModel: () => ({ modelId }) as never },
  136. },
  137. }),
  138. retry: { maxAttempts: 1 },
  139. runtime: {
  140. async generateText() {
  141. return { ...completion, text: overflow ? "" : "done", usage } as never;
  142. },
  143. streamText() {
  144. return {
  145. fullStream: (async function* () {
  146. yield { type: "start" };
  147. if (!overflow) yield { type: "text-delta", id: "text", text: "done" };
  148. yield { type: "finish", ...completion, totalUsage: usage };
  149. })(),
  150. } as never;
  151. },
  152. },
  153. });
  154. const options = {
  155. providerId,
  156. modelId,
  157. messages: [{ role: "user" as const, content: "Continue" }],
  158. metadata: { querySource },
  159. statusSink: {
  160. publish(status: ModelNetworkStatusEvent) {
  161. statuses.push(status);
  162. publish(SessionEventType.ModelNetworkStatus, status);
  163. },
  164. },
  165. };
  166. const run = async () => {
  167. if (mode === "generate") return executeAdapterGenerateText(adapter, options);
  168. for await (const _event of executeAdapterStreamText(adapter, options)) {
  169. /* consume provider stream */
  170. }
  171. };
  172. if (overflow) {
  173. await expect(run()).rejects.toMatchObject({ code: ModelErrorCode.ModelContextExceeded });
  174. expect(statuses.filter((status) => status.type === "model_request_failed")).toHaveLength(
  175. 1,
  176. );
  177. expect(statuses.some((status) => status.type === "model_request_completed")).toBe(false);
  178. return;
  179. }
  180. await run();
  181. const completed = statuses.find((status) => status.type === "model_request_completed")!;
  182. const fact = publish(SessionEventType.ModelComplete, {
  183. content: "done",
  184. stopReason: "stop",
  185. querySource,
  186. usage,
  187. });
  188. if (querySource === "compact") expect(fact).toBeNull();
  189. else
  190. expect(fact).toMatchObject({
  191. kind: "usage.delta",
  192. requestId: completed.requestId,
  193. providerId,
  194. modelId,
  195. totalTokens,
  196. turnId,
  197. });
  198. }
  199. await request("A", 85, "main_turn", true);
  200. if (outcome === "success") {
  201. await request("B", 112, "compact");
  202. await request("C", 104);
  203. }
  204. publish(
  205. outcome === "failed" ? SessionEventType.TurnError : SessionEventType.TurnComplete,
  206. outcome === "failed"
  207. ? {
  208. error: {
  209. type: "model_context_exceeded",
  210. message: "Compact failed",
  211. retryable: false,
  212. },
  213. }
  214. : { resultType: outcome, duration: 10, tokenCount: 301, toolCallCount: 0 },
  215. );
  216. turnId = "turn-2";
  217. await request("D", 20);
  218. },
  219. );
  220. });
  221. // 冻结 a129878ef5 的旧 strict 分支白名单,不能从当前 schema 动态生成。
  222. const legacyBaseKeys = [
  223. "memoryEnabled",
  224. "version",
  225. "eventId",
  226. "eventSeq",
  227. "occurredAt",
  228. "sessionId",
  229. "sourceCommandId",
  230. "turnId",
  231. "kind",
  232. ];
  233. const frozenLegacySchema = (keys: string[]) =>
  234. z
  235. .object(
  236. Object.fromEntries([...legacyBaseKeys, ...keys].map((key) => [key, z.unknown().optional()])),
  237. )
  238. .strict();
  239. const legacyStarted = frozenLegacySchema([
  240. "inputOrigin",
  241. "modelName",
  242. "modelProvider",
  243. "executionKind",
  244. "inputSource",
  245. "backgroundSource",
  246. "automationId",
  247. "offPeakTaskId",
  248. "offPeakRunType",
  249. "taskTrigger",
  250. "scheduledAt",
  251. ]);
  252. const legacyUsage = frozenLegacySchema([
  253. "requestId",
  254. "providerId",
  255. "modelId",
  256. "providerKind",
  257. "providerHostname",
  258. "inputTokens",
  259. "outputTokens",
  260. "totalTokens",
  261. "reasoningTokens",
  262. "cacheReadTokens",
  263. "cacheWriteTokens",
  264. ]);
  265. describe("首响独立通知兼容旧 strict fact", () => {
  266. it.each([
  267. [true, "startNow", "direct"],
  268. [false, "queue", "queued"],
  269. ] as const)("首条=%s / %s 只放独立 admission", (isFirstMessage, admittedDelivery, sendMode) => {
  270. const normalizer = new ConversationTelemetryFactNormalizer();
  271. const raw = event(
  272. SessionEventType.TurnStarted,
  273. { inputId: "command", isFirstMessage, intent: { admittedDelivery } },
  274. 1,
  275. );
  276. const wire = normalizer.normalize("parent", raw);
  277. expect(legacyStarted.safeParse(wire).success).toBe(true);
  278. expect(wire).not.toHaveProperty("isFirstMessage");
  279. expect(wire).not.toHaveProperty("sendMode");
  280. expect(normalizer.normalizeTurnAdmission("parent", raw)).toMatchObject({
  281. sourceCommandId: "command",
  282. isFirstMessage,
  283. sendMode,
  284. });
  285. // 守护测试自身必须能识别本次审核发现的退化。
  286. expect(legacyStarted.safeParse({ ...wire, isFirstMessage }).success).toBe(false);
  287. });
  288. it("guide 不映射 direct,缺事实不发空补充通知", () => {
  289. const normalizer = new ConversationTelemetryFactNormalizer();
  290. const raw = event(
  291. SessionEventType.TurnStarted,
  292. { inputId: "c", intent: { admittedDelivery: "guide" } },
  293. 1,
  294. );
  295. normalizer.normalize("parent", raw);
  296. expect(normalizer.normalizeTurnAdmission("parent", raw)).toBeNull();
  297. });
  298. it.each([undefined, 0, 9])("usage 旧格式不变,独立 metrics 保留 cache=%s", (cacheReadTokens) => {
  299. const normalizer = new ConversationTelemetryFactNormalizer();
  300. const raw = event(
  301. SessionEventType.ModelNetworkStatus,
  302. {
  303. type: "model_request_completed",
  304. requestId: "r",
  305. providerId: "p",
  306. modelId: "m",
  307. transport: "http",
  308. attempt: 1,
  309. maxAttempts: 2,
  310. durationMs: 10,
  311. querySource: "main_turn",
  312. usage: { inputTokens: 12, cacheReadTokens },
  313. },
  314. 1,
  315. );
  316. normalizer.normalize("parent", raw);
  317. const metrics = normalizer.normalizeModelRequestMetrics("parent", raw);
  318. expect(metrics).toMatchObject({ requestId: "r", inputTokens: 12 });
  319. if (cacheReadTokens === undefined) expect(metrics).not.toHaveProperty("cacheReadTokens");
  320. else expect(metrics?.cacheReadTokens).toBe(cacheReadTokens);
  321. const wire = normalizer.normalize(
  322. "parent",
  323. event(
  324. SessionEventType.ModelComplete,
  325. { querySource: "main_turn", usage: { inputTokens: 12, cacheReadTokens } },
  326. 2,
  327. ),
  328. );
  329. expect(legacyUsage.safeParse(wire).success).toBe(true);
  330. expect(wire).not.toHaveProperty("ttftInputTokens");
  331. expect(wire).not.toHaveProperty("ttftCachedInputTokens");
  332. expect(legacyUsage.safeParse({ ...wire, ttftInputTokens: 12 }).success).toBe(false);
  333. });
  334. it("metrics 沿用 cacheTokens 回退并保留 input 缺失", () => {
  335. const n = new ConversationTelemetryFactNormalizer();
  336. const raw = event(
  337. SessionEventType.ModelNetworkStatus,
  338. {
  339. type: "model_request_completed",
  340. requestId: "r",
  341. providerId: "p",
  342. modelId: "m",
  343. durationMs: 10,
  344. usage: { cacheTokens: 9 },
  345. },
  346. 1,
  347. );
  348. const fact = n.normalizeModelRequestMetrics("parent", raw);
  349. expect(fact).toMatchObject({ cacheReadTokens: 9 });
  350. expect(fact).not.toHaveProperty("inputTokens");
  351. });
  352. });