conversation-telemetry-parity.mjs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /* oxlint-disable eslint(max-lines) -- final payload 的归一化、关系验证和结构化 diff 必须共享同一字段表,拆文件会让白名单与 invariant 漂移。 */
  2. // 纯数据比较器:可由 Vitest、WDIO 或独立 Node runner 复用,不依赖测试框架全局变量。
  3. export const CONVERSATION_TELEMETRY_DIFF_CATEGORIES = [
  4. "MISSING_EVENT",
  5. "EXTRA_EVENT",
  6. "MISSING_FIELD",
  7. "EXTRA_FIELD",
  8. "TYPE_MISMATCH",
  9. "VALUE_MISMATCH",
  10. "RELATION_MISMATCH",
  11. "ORDER_MISMATCH",
  12. "TIMING_INVARIANT_MISMATCH",
  13. ];
  14. const CATEGORY_ORDER = new Map(
  15. CONVERSATION_TELEMETRY_DIFF_CATEGORIES.map((category, index) => [category, index]),
  16. );
  17. const MISSING_VALUE = Symbol("conversation-telemetry-missing");
  18. // event_id/event_key 只标识单次上报,没有任何下游字段会引用它们。旧版并发执行
  19. // reportEvent 时,不同事件拿到 ID 和完成 fetch 的顺序并不稳定,因此这里只保留字段与类型,
  20. // 不给单次事件 ID 建立跨事件关系;真正需要验证关联的 request/message/session 等仍使用稳定 alias。
  21. const NON_RELATIONAL_EVENT_ID_KEYS = new Set(["event_id", "eventId", "event_key", "eventKey"]);
  22. const ID_KIND_BY_KEY = new Map([
  23. ["device_mid", "device"],
  24. ["deviceMid", "device"],
  25. ["event_id", "event"],
  26. ["eventId", "event"],
  27. ["event_key", "event"],
  28. ["eventKey", "event"],
  29. ["input_id", "input"],
  30. ["inputId", "input"],
  31. ["message_id", "message"],
  32. ["messageId", "message"],
  33. ["assistant_message_id", "message"],
  34. ["assistantMessageId", "message"],
  35. ["source_command_id", "message"],
  36. ["sourceCommandId", "message"],
  37. ["summary_message_id", "message"],
  38. ["summaryMessageId", "message"],
  39. ["entity_id", "message"],
  40. ["entityId", "message"],
  41. ["renderer_id", "renderer"],
  42. ["rendererId", "renderer"],
  43. ["query_id", "query"],
  44. ["queryId", "query"],
  45. ["request_id", "request"],
  46. ["requestId", "request"],
  47. ["session_id", "session"],
  48. ["sessionId", "session"],
  49. ["task_id", "session"],
  50. ["taskId", "session"],
  51. ["talk_id", "session"],
  52. ["talkId", "session"],
  53. ["child_session_id", "session"],
  54. ["childSessionId", "session"],
  55. ["tool_call_id", "tool"],
  56. ["toolCallId", "tool"],
  57. ["tool_id", "tool"],
  58. ["toolId", "tool"],
  59. ["parent_tool_call_id", "tool"],
  60. ["parentToolCallId", "tool"],
  61. ["child_tool_call_id", "tool"],
  62. ["childToolCallId", "tool"],
  63. ["turn_id", "turn"],
  64. ["turnId", "turn"],
  65. ["product_turn_id", "turn"],
  66. ["productTurnId", "turn"],
  67. // agent_step 的 step_id 是 renderer 生成的 turn 内不透明标识,也必须跨旧版/V4 归一。
  68. ["step_id", "turn"],
  69. ["stepId", "turn"],
  70. ]);
  71. const APP_VERSION_KEYS = new Set(["app_version", "appVersion"]);
  72. const TIMESTAMP_KEYS = new Set(["timestamp"]);
  73. const ABSOLUTE_TIME_KEYS = new Set([
  74. "input_first_char_time",
  75. "input_send_time",
  76. "input_start_time",
  77. "request_time",
  78. ]);
  79. const TIMING_VALUE_KEYS = new Set([
  80. "duration_ms",
  81. "generation_tail_finalize_ms",
  82. "metric_value",
  83. "stall_ms",
  84. "time_to_first_token",
  85. "total_ms",
  86. "ttft_ms",
  87. "waiting_ms",
  88. ]);
  89. const TIMING_ARMS_EVENTS = new Set([
  90. "plan_request",
  91. "plan_ttft",
  92. "perf_ui_first_token",
  93. "perf_ui_message_complete",
  94. "perf_ui_stream_stall",
  95. "perf_ui_tool_call_detail",
  96. "perf_ui_turn_breakdown",
  97. ]);
  98. class StableAliasRegistry {
  99. constructor() {
  100. /** @type {Map<string, Map<string, number>>} */
  101. this.aliases = new Map();
  102. }
  103. /**
  104. * @param {string} kind
  105. * @param {unknown} value
  106. * @returns {unknown}
  107. */
  108. normalize(kind, value) {
  109. if ((typeof value !== "string" && typeof value !== "number") || value === "") {
  110. return value;
  111. }
  112. const typedKey = `${typeof value}:${String(value)}`;
  113. let aliasesForKind = this.aliases.get(kind);
  114. if (!aliasesForKind) {
  115. aliasesForKind = new Map();
  116. this.aliases.set(kind, aliasesForKind);
  117. }
  118. let alias = aliasesForKind.get(typedKey);
  119. if (alias === undefined) {
  120. alias = aliasesForKind.size + 1;
  121. aliasesForKind.set(typedKey, alias);
  122. }
  123. return typeof value === "number" ? alias : `<${kind}:${alias}>`;
  124. }
  125. }
  126. /**
  127. * @param {string} key
  128. * @param {unknown} value
  129. * @returns {unknown}
  130. */
  131. function normalizeDynamicScalar(key, value, context) {
  132. if (APP_VERSION_KEYS.has(key)) {
  133. if (typeof value === "string") return "<app-version>";
  134. if (typeof value === "number") return 0;
  135. }
  136. if (TIMESTAMP_KEYS.has(key)) {
  137. if (typeof value === "string") return "<timestamp>";
  138. if (typeof value === "number") return 0;
  139. }
  140. if (ABSOLUTE_TIME_KEYS.has(key)) {
  141. if (typeof value === "string" && value !== "") return "<absolute-time>";
  142. if (typeof value === "number") return 0;
  143. }
  144. const isStartedPlanMetric =
  145. context.channel === "arms" &&
  146. context.eventName === "plan_request" &&
  147. context.requestStatus === "started" &&
  148. (key === "metric_value" || key === "value");
  149. const isArmsTimingValue =
  150. key === "value" && context.channel === "arms" && TIMING_ARMS_EVENTS.has(context.eventName);
  151. // 旧版 reasoning 的开始/结束由两条异步 renderer 回调分别取 Date.now()。即使 SSE fixture
  152. // 留出了稳定间隔,事件循环仍可能把它们压到同一毫秒,因此这里只比较非负性;generation、
  153. // tool 等 step 的历史固定零值仍按原值严格比较,避免把真正的口径变化归一掉。
  154. const isReasoningStepDuration =
  155. context.channel === "report" &&
  156. context.eventName === "agent_step" &&
  157. context.stepType === "reasoning" &&
  158. key === "duration_ms";
  159. if (isReasoningStepDuration) {
  160. const numeric = numericValue(value);
  161. if (numeric !== null && numeric >= 0) {
  162. return typeof value === "number" ? 3 : "<nonnegative-reasoning-timing>";
  163. }
  164. }
  165. if (!isStartedPlanMetric && (TIMING_VALUE_KEYS.has(key) || isArmsTimingValue)) {
  166. const numeric = numericValue(value);
  167. if (numeric !== null && numeric > 0) {
  168. return typeof value === "number" ? 2 : "<positive-timing>";
  169. }
  170. }
  171. if (
  172. context.channel === "report" &&
  173. context.eventName === "context_compaction" &&
  174. (key === "pre_compact_tokens" || key === "true_post_compact_tokens")
  175. ) {
  176. const numeric = numericValue(value);
  177. if (numeric !== null && numeric > 0) {
  178. return typeof value === "number" ? 2 : "<positive-runtime-token-watermark>";
  179. }
  180. }
  181. return value;
  182. }
  183. /**
  184. * @param {unknown} value
  185. * @param {string | null} key
  186. * @param {StableAliasRegistry} aliases
  187. * @returns {unknown}
  188. */
  189. function normalizeValue(value, key, aliases, context) {
  190. if (key && NON_RELATIONAL_EVENT_ID_KEYS.has(key) && value !== "") {
  191. if (typeof value === "string") return "<event-id>";
  192. if (typeof value === "number") return 0;
  193. }
  194. const aliasKind = key ? ID_KIND_BY_KEY.get(key) : undefined;
  195. if (aliasKind) {
  196. return aliases.normalize(aliasKind, value);
  197. }
  198. if (key) {
  199. const normalizedDynamic = normalizeDynamicScalar(key, value, context);
  200. if (normalizedDynamic !== value) return normalizedDynamic;
  201. }
  202. if (Array.isArray(value)) {
  203. return value.map((item) => normalizeValue(item, null, aliases, context));
  204. }
  205. if (isRecord(value)) {
  206. /** @type {Record<string, unknown>} */
  207. const normalized = {};
  208. for (const propertyKey of Object.keys(value)) {
  209. normalized[propertyKey] = normalizeValue(value[propertyKey], propertyKey, aliases, context);
  210. }
  211. return normalized;
  212. }
  213. return value;
  214. }
  215. /**
  216. * 每次调用使用独立 alias registry;同一次 capture 的 report/ARMS 共享关联表。
  217. * @param {{ report: readonly unknown[]; arms: readonly unknown[] }} capture
  218. * @returns {{ report: unknown[]; arms: unknown[] }}
  219. */
  220. export function normalizeConversationTelemetryCapture(capture) {
  221. const aliases = new StableAliasRegistry();
  222. return {
  223. report: capture.report.map((payload) =>
  224. normalizeValue(payload, null, aliases, normalizationContext("report", payload)),
  225. ),
  226. arms: capture.arms.map((payload) =>
  227. normalizeValue(payload, null, aliases, normalizationContext("arms", payload)),
  228. ),
  229. };
  230. }
  231. /** @param {"report" | "arms"} channel @param {unknown} payload */
  232. function normalizationContext(channel, payload) {
  233. const properties = isRecord(payload) && isRecord(payload.properties) ? payload.properties : null;
  234. const reportDetail =
  235. isRecord(payload) && isRecord(payload.event_extra_detail) ? payload.event_extra_detail : null;
  236. return {
  237. channel,
  238. eventName: eventName(channel, payload),
  239. requestStatus: readNonEmptyString(properties?.request_status) ?? "",
  240. stepType: readNonEmptyString(reportDetail?.step_type) ?? "",
  241. };
  242. }
  243. /**
  244. * @param {"report" | "arms"} channel
  245. * @param {unknown} payload
  246. * @returns {string}
  247. */
  248. function eventName(channel, payload) {
  249. if (!isRecord(payload)) return `<invalid:${valueType(payload)}>`;
  250. if (channel === "report") {
  251. return (
  252. readNonEmptyString(payload.element_name) ??
  253. readNonEmptyString(payload.elementName) ??
  254. "<unknown>"
  255. );
  256. }
  257. const properties = isRecord(payload.properties) ? payload.properties : null;
  258. return (
  259. readNonEmptyString(payload.name) ??
  260. readNonEmptyString(payload.event_name) ??
  261. readNonEmptyString(properties?.event_name) ??
  262. "<unknown>"
  263. );
  264. }
  265. /**
  266. * @param {readonly unknown[]} events
  267. * @param {"report" | "arms"} channel
  268. * @returns {Map<string, number>}
  269. */
  270. function inventory(events, channel) {
  271. /** @type {Map<string, number>} */
  272. const counts = new Map();
  273. for (const event of events) {
  274. const name = eventName(channel, event);
  275. counts.set(name, (counts.get(name) ?? 0) + 1);
  276. }
  277. return counts;
  278. }
  279. /**
  280. * @param {"report" | "arms"} channel
  281. * @param {readonly unknown[]} expected
  282. * @param {readonly unknown[]} actual
  283. * @param {Array<ConversationTelemetryParityDiff>} differences
  284. */
  285. function compareChannel(channel, expected, actual, differences) {
  286. const expectedInventory = inventory(expected, channel);
  287. const actualInventory = inventory(actual, channel);
  288. const inventoryNames = [
  289. ...new Set([...expectedInventory.keys(), ...actualInventory.keys()]),
  290. ].sort();
  291. let inventoryMatches = true;
  292. for (const name of inventoryNames) {
  293. const expectedCount = expectedInventory.get(name) ?? 0;
  294. const actualCount = actualInventory.get(name) ?? 0;
  295. if (expectedCount === actualCount) continue;
  296. inventoryMatches = false;
  297. differences.push(
  298. createDiff({
  299. category: actualCount < expectedCount ? "MISSING_EVENT" : "EXTRA_EVENT",
  300. channel,
  301. eventIndex: null,
  302. path: `${channel}.inventory[${JSON.stringify(name)}]`,
  303. expected: expectedCount,
  304. actual: actualCount,
  305. }),
  306. );
  307. }
  308. const expectedByName = groupEventsByName(expected, channel);
  309. const actualByName = groupEventsByName(actual, channel);
  310. for (const name of inventoryNames) {
  311. const expectedEvents = expectedByName.get(name) ?? [];
  312. const actualEvents = actualByName.get(name) ?? [];
  313. const comparableLength = Math.min(expectedEvents.length, actualEvents.length);
  314. const expectedOrder = expectedEvents.map(({ payload }) =>
  315. stableEventOrderSignature(channel, payload),
  316. );
  317. const actualOrder = actualEvents.map(({ payload }) =>
  318. stableEventOrderSignature(channel, payload),
  319. );
  320. const stableOrderMatches = comparableLength <= 1 || sameStringArray(expectedOrder, actualOrder);
  321. if (inventoryMatches && !stableOrderMatches) {
  322. differences.push(
  323. createDiff({
  324. category: "ORDER_MISMATCH",
  325. channel,
  326. eventIndex: null,
  327. path: `${channel}.order[${JSON.stringify(name)}]`,
  328. expected: expectedOrder,
  329. actual: actualOrder,
  330. }),
  331. );
  332. continue;
  333. }
  334. for (let occurrence = 0; occurrence < comparableLength; occurrence += 1) {
  335. const expectedEvent = expectedEvents[occurrence];
  336. const actualEvent = actualEvents[occurrence];
  337. compareValue(
  338. expectedEvent.payload,
  339. actualEvent.payload,
  340. `${channel}[${expectedEvent.index}]`,
  341. channel,
  342. expectedEvent.index,
  343. differences,
  344. null,
  345. );
  346. }
  347. }
  348. }
  349. /**
  350. * 旧版同一个 terminal 会 fire-and-forget 两次异步 reportEvent;agent_step 与
  351. * message_completion 谁先完成网络请求不是统计口径。比较时按事件名配对,但同一事件名内部仍
  352. * 保留业务阶段顺序,例如 plan_request 的 started 必须先于 completed。
  353. * @param {readonly unknown[]} events
  354. * @param {"report" | "arms"} channel
  355. */
  356. function groupEventsByName(events, channel) {
  357. /** @type {Map<string, Array<{ index: number; payload: unknown }>>} */
  358. const grouped = new Map();
  359. events.forEach((payload, index) => {
  360. const name = eventName(channel, payload);
  361. const group = grouped.get(name) ?? [];
  362. group.push({ index, payload });
  363. grouped.set(name, group);
  364. });
  365. return grouped;
  366. }
  367. /** @param {"report" | "arms"} channel @param {unknown} payload */
  368. function stableEventOrderSignature(channel, payload) {
  369. if (!isRecord(payload)) return `<invalid:${valueType(payload)}>`;
  370. const detail =
  371. channel === "report"
  372. ? isRecord(payload.event_extra_detail)
  373. ? payload.event_extra_detail
  374. : isRecord(payload.eventExtraDetail)
  375. ? payload.eventExtraDetail
  376. : null
  377. : isRecord(payload.properties)
  378. ? payload.properties
  379. : null;
  380. if (!detail) return eventName(channel, payload);
  381. const fields =
  382. channel === "report"
  383. ? [detail.loop_index, detail.step_type, detail.tool_name, detail.status]
  384. : [detail.request_status, detail.result, detail.tool_name, detail.status];
  385. return JSON.stringify([eventName(channel, payload), ...fields.map((value) => value ?? null)]);
  386. }
  387. /**
  388. * @param {unknown} expected
  389. * @param {unknown} actual
  390. * @param {string} path
  391. * @param {"report" | "arms"} channel
  392. * @param {number} eventIndex
  393. * @param {Array<ConversationTelemetryParityDiff>} differences
  394. * @param {string | null} propertyKey
  395. */
  396. function compareValue(expected, actual, path, channel, eventIndex, differences, propertyKey) {
  397. const expectedType = valueType(expected);
  398. const actualType = valueType(actual);
  399. if (expectedType !== actualType) {
  400. differences.push(
  401. createDiff({
  402. category: "TYPE_MISMATCH",
  403. channel,
  404. eventIndex,
  405. path,
  406. expected,
  407. actual,
  408. }),
  409. );
  410. return;
  411. }
  412. if (Array.isArray(expected) && Array.isArray(actual)) {
  413. if (expected.length !== actual.length) {
  414. differences.push(
  415. createDiff({
  416. category: "VALUE_MISMATCH",
  417. channel,
  418. eventIndex,
  419. path: `${path}.length`,
  420. expected: expected.length,
  421. actual: actual.length,
  422. }),
  423. );
  424. }
  425. const length = Math.min(expected.length, actual.length);
  426. for (let index = 0; index < length; index += 1) {
  427. compareValue(
  428. expected[index],
  429. actual[index],
  430. `${path}[${index}]`,
  431. channel,
  432. eventIndex,
  433. differences,
  434. null,
  435. );
  436. }
  437. return;
  438. }
  439. if (isRecord(expected) && isRecord(actual)) {
  440. const expectedKeys = Object.keys(expected).sort();
  441. const actualKeys = Object.keys(actual).sort();
  442. const allKeys = [...new Set([...expectedKeys, ...actualKeys])].sort();
  443. for (const key of allKeys) {
  444. const expectedHasKey = Object.hasOwn(expected, key);
  445. const actualHasKey = Object.hasOwn(actual, key);
  446. const childPath = appendPath(path, key);
  447. if (!expectedHasKey || !actualHasKey) {
  448. differences.push(
  449. createDiff({
  450. category: expectedHasKey ? "MISSING_FIELD" : "EXTRA_FIELD",
  451. channel,
  452. eventIndex,
  453. path: childPath,
  454. expected: expectedHasKey ? expected[key] : MISSING_VALUE,
  455. actual: actualHasKey ? actual[key] : MISSING_VALUE,
  456. }),
  457. );
  458. continue;
  459. }
  460. compareValue(expected[key], actual[key], childPath, channel, eventIndex, differences, key);
  461. }
  462. return;
  463. }
  464. if (!Object.is(expected, actual)) {
  465. differences.push(
  466. createDiff({
  467. category:
  468. propertyKey && ID_KIND_BY_KEY.has(propertyKey)
  469. ? "RELATION_MISMATCH"
  470. : propertyKey &&
  471. (TIMING_VALUE_KEYS.has(propertyKey) ||
  472. (channel === "arms" && propertyKey === "value"))
  473. ? "TIMING_INVARIANT_MISMATCH"
  474. : "VALUE_MISMATCH",
  475. channel,
  476. eventIndex,
  477. path,
  478. expected,
  479. actual,
  480. }),
  481. );
  482. }
  483. }
  484. /**
  485. * duration 的墙钟值可以因 Electron/CI 调度不同而变化,但每份 capture 内的旧公式必须成立。
  486. * @param {{ report: readonly unknown[]; arms: readonly unknown[] }} capture
  487. */
  488. function collectTimingInvariantIssues(capture) {
  489. /** @type {{ report: string[]; arms: string[] }} */
  490. const issues = { report: [], arms: [] };
  491. /** @type {Map<string, number>} */
  492. const sendTimeByMessage = new Map();
  493. /** @type {{ duration: number | null; ttft: number | null; messageKey: string }[]} */
  494. const completions = [];
  495. capture.report.forEach((payload, index) => {
  496. if (!isRecord(payload)) return;
  497. const name = eventName("report", payload);
  498. const detail = isRecord(payload.event_extra_detail)
  499. ? payload.event_extra_detail
  500. : isRecord(payload.eventExtraDetail)
  501. ? payload.eventExtraDetail
  502. : null;
  503. if (!detail) return;
  504. const messageKey = reportMessageKey(payload);
  505. if (name === "send_btn") {
  506. const start = numericValue(detail.input_start_time);
  507. const first = numericValue(detail.input_first_char_time);
  508. const send = numericValue(detail.input_send_time);
  509. if (start !== null && first !== null && send !== null && !(start <= first && first <= send)) {
  510. issues.report.push(`report[${index}] send input_start<=input_first_char<=input_send`);
  511. }
  512. if (messageKey && send !== null) sendTimeByMessage.set(messageKey, send);
  513. return;
  514. }
  515. if (name === "agent_step") {
  516. const duration = numericValue(detail.duration_ms);
  517. const tail = numericValue(detail.generation_tail_finalize_ms);
  518. if (duration !== null && duration < 0) {
  519. issues.report.push(`report[${index}] agent_step duration_ms>=0`);
  520. }
  521. if (tail !== null && (tail < 0 || (duration !== null && tail > duration))) {
  522. issues.report.push(`report[${index}] 0<=generation_tail_finalize_ms<=duration_ms`);
  523. }
  524. return;
  525. }
  526. if (name === "context_compaction") {
  527. const pre = numericValue(detail.pre_compact_tokens);
  528. const post = numericValue(detail.post_compact_tokens);
  529. const truePost = numericValue(detail.true_post_compact_tokens);
  530. const ratio = numericValue(detail.compact_ratio);
  531. if (
  532. [pre, post, truePost].some((value) => value !== null && value < 0)
  533. ) {
  534. issues.report.push(`report[${index}] compaction token watermarks>=0`);
  535. }
  536. if (
  537. pre !== null &&
  538. pre > 0 &&
  539. post !== null &&
  540. ratio !== null &&
  541. ratio !== Number((post / pre).toFixed(4))
  542. ) {
  543. issues.report.push(`report[${index}] compact_ratio=post_compact_tokens/pre_compact_tokens`);
  544. }
  545. return;
  546. }
  547. if (name !== "message_completion") return;
  548. const duration = numericValue(detail.duration_ms);
  549. const ttft = numericValue(detail.time_to_first_token);
  550. const requestTime = numericValue(detail.request_time);
  551. if (duration !== null && duration < 0) {
  552. issues.report.push(`report[${index}] completion duration_ms>=0`);
  553. }
  554. if (ttft !== null && ttft !== -1 && (ttft < 0 || (duration !== null && ttft > duration))) {
  555. issues.report.push(`report[${index}] completion ttft=-1 or 0<=ttft<=duration`);
  556. }
  557. const sendTime = messageKey ? sendTimeByMessage.get(messageKey) : undefined;
  558. if (requestTime !== null && sendTime !== undefined && requestTime !== sendTime) {
  559. issues.report.push(`report[${index}] request_time=input_send_time`);
  560. }
  561. completions.push({ duration, ttft, messageKey: messageKey ?? `#${index}` });
  562. });
  563. let planTtftIndex = 0;
  564. capture.arms.forEach((payload, index) => {
  565. if (!isRecord(payload)) return;
  566. const name = eventName("arms", payload);
  567. const properties = isRecord(payload.properties) ? payload.properties : null;
  568. if (!properties) return;
  569. const value = numericValue(payload.value);
  570. const metric = numericValue(properties.metric_value);
  571. if (value !== null && metric !== null && value !== metric) {
  572. issues.arms.push(`arms[${index}] value=metric_value`);
  573. }
  574. if (name === "plan_request") {
  575. const status = readNonEmptyString(properties.request_status);
  576. const duration = numericValue(properties.duration_ms);
  577. if (status === "started" && value !== null && value !== 1) {
  578. issues.arms.push(`arms[${index}] plan_request started value=1`);
  579. }
  580. if (status === "completed" && duration !== null && value !== null && duration !== value) {
  581. issues.arms.push(`arms[${index}] plan_request completed duration_ms=value`);
  582. }
  583. return;
  584. }
  585. if (name === "plan_ttft") {
  586. const ttft = numericValue(properties.ttft_ms);
  587. if (value !== null && (value < 0 || (ttft !== null && ttft !== value))) {
  588. issues.arms.push(`arms[${index}] plan_ttft 0<=ttft_ms=value`);
  589. }
  590. const completion = completions[planTtftIndex];
  591. if (
  592. completion?.ttft !== null &&
  593. completion?.ttft !== undefined &&
  594. value !== null &&
  595. completion.ttft !== value
  596. ) {
  597. issues.arms.push(`arms[${index}] plan_ttft=completion.time_to_first_token`);
  598. }
  599. planTtftIndex += 1;
  600. return;
  601. }
  602. if (name === "perf_ui_first_token") {
  603. if (value !== null && value < 0) {
  604. issues.arms.push(`arms[${index}] perf_ui_first_token value>=0`);
  605. }
  606. compareMessageTimingToCompletion({
  607. payload,
  608. value,
  609. field: "ttft",
  610. invariant: "perf_ui_first_token=completion.time_to_first_token",
  611. index,
  612. completions,
  613. issues: issues.arms,
  614. });
  615. return;
  616. }
  617. if (name === "perf_ui_message_complete") {
  618. compareMessageTimingToCompletion({
  619. payload,
  620. value,
  621. field: "duration",
  622. invariant: "perf_ui_message_complete=completion.duration_ms",
  623. index,
  624. completions,
  625. issues: issues.arms,
  626. });
  627. return;
  628. }
  629. if (name === "perf_ui_stream_stall") {
  630. const stall = numericValue(properties.stall_ms);
  631. if (stall !== null && (stall <= 3000 || (value !== null && stall !== value))) {
  632. issues.arms.push(`arms[${index}] stream_stall stall_ms=value>3000`);
  633. }
  634. return;
  635. }
  636. if (name === "perf_ui_tool_call_detail") {
  637. const total = numericValue(properties.total_ms);
  638. if (total !== null && (total < 0 || (value !== null && total !== value))) {
  639. issues.arms.push(`arms[${index}] tool_call_detail total_ms=value>=0`);
  640. }
  641. return;
  642. }
  643. if (name !== "perf_ui_turn_breakdown") return;
  644. const duration = numericValue(properties.duration_ms);
  645. const ttft = numericValue(properties.ttft_ms);
  646. if (value !== null && duration !== null && value !== duration) {
  647. issues.arms.push(`arms[${index}] turn_breakdown duration_ms=value`);
  648. }
  649. if (duration !== null && ttft !== null && (ttft < 0 || ttft > duration)) {
  650. issues.arms.push(`arms[${index}] turn_breakdown 0<=ttft_ms<=duration_ms`);
  651. }
  652. compareMessageTimingToCompletion({
  653. payload,
  654. value,
  655. field: "duration",
  656. invariant: "turn_breakdown=completion.duration_ms",
  657. index,
  658. completions,
  659. issues: issues.arms,
  660. });
  661. });
  662. return issues;
  663. }
  664. /** @param {{ payload: Record<string, unknown>; value: number | null; field: "duration" | "ttft"; invariant: string; index: number; completions: { duration: number | null; ttft: number | null; messageKey: string }[]; issues: string[] }} input */
  665. function compareMessageTimingToCompletion(input) {
  666. if (input.value === null) return;
  667. const messageKey = armsMessageKey(input.payload);
  668. if (!messageKey) return;
  669. const completion = input.completions.find((candidate) => candidate.messageKey === messageKey);
  670. const expected = completion?.[input.field];
  671. if (expected !== null && expected !== undefined && expected !== input.value) {
  672. input.issues.push(`arms[${input.index}] ${input.invariant}`);
  673. }
  674. }
  675. /** @param {Record<string, unknown>} payload */
  676. function reportMessageKey(payload) {
  677. const talk = readScalar(payload.talk_id ?? payload.talkId);
  678. const message = readScalar(payload.message_id ?? payload.messageId);
  679. return talk !== null && message !== null ? `${talk}\0${message}` : null;
  680. }
  681. /** @param {Record<string, unknown>} payload */
  682. function armsMessageKey(payload) {
  683. const properties = isRecord(payload.properties) ? payload.properties : null;
  684. if (!properties) return null;
  685. const talk = readScalar(properties.talk_id ?? properties.talkId);
  686. const message = readScalar(properties.message_id ?? properties.messageId);
  687. return talk !== null && message !== null ? `${talk}\0${message}` : null;
  688. }
  689. /** @param {unknown} value */
  690. function numericValue(value) {
  691. if (typeof value === "number") return Number.isFinite(value) ? value : null;
  692. if (typeof value !== "string" || value.trim() === "") return null;
  693. const parsed = Number(value);
  694. return Number.isFinite(parsed) ? parsed : null;
  695. }
  696. /** @param {unknown} value */
  697. function readScalar(value) {
  698. return typeof value === "string" || typeof value === "number" ? String(value) : null;
  699. }
  700. /**
  701. * @param {{ report: string[]; arms: string[] }} expected
  702. * @param {{ report: string[]; arms: string[] }} actual
  703. * @param {Array<ConversationTelemetryParityDiff>} differences
  704. */
  705. function compareTimingInvariantIssues(expected, actual, differences) {
  706. for (const channel of ["report", "arms"]) {
  707. if (sameStringArray(expected[channel], actual[channel])) continue;
  708. differences.push(
  709. createDiff({
  710. category: "TIMING_INVARIANT_MISMATCH",
  711. channel,
  712. eventIndex: null,
  713. path: `${channel}.timing_invariants`,
  714. expected: expected[channel],
  715. actual: actual[channel],
  716. }),
  717. );
  718. }
  719. }
  720. /**
  721. * @param {{ report: readonly unknown[]; arms: readonly unknown[] }} expectedCapture
  722. * @param {{ report: readonly unknown[]; arms: readonly unknown[] }} actualCapture
  723. * @returns {ConversationTelemetryParityResult}
  724. */
  725. export function compareConversationTelemetryParity(expectedCapture, actualCapture) {
  726. const expectedTimingIssues = collectTimingInvariantIssues(expectedCapture);
  727. const actualTimingIssues = collectTimingInvariantIssues(actualCapture);
  728. const expected = normalizeConversationTelemetryCapture(expectedCapture);
  729. const actual = normalizeConversationTelemetryCapture(actualCapture);
  730. /** @type {Array<ConversationTelemetryParityDiff>} */
  731. const differences = [];
  732. compareChannel("report", expected.report, actual.report, differences);
  733. compareChannel("arms", expected.arms, actual.arms, differences);
  734. compareTimingInvariantIssues(expectedTimingIssues, actualTimingIssues, differences);
  735. differences.sort(compareDifferences);
  736. return { equal: differences.length === 0, expected, actual, differences };
  737. }
  738. /**
  739. * @param {readonly ConversationTelemetryParityDiff[]} differences
  740. * @returns {string}
  741. */
  742. export function formatConversationTelemetryParityDifferences(differences) {
  743. return differences
  744. .map(
  745. (difference) =>
  746. `[${difference.category}] ${difference.path}: expected=${difference.expected} actual=${difference.actual}`,
  747. )
  748. .join("\n");
  749. }
  750. /**
  751. * @param {{ report: readonly unknown[]; arms: readonly unknown[] }} expected
  752. * @param {{ report: readonly unknown[]; arms: readonly unknown[] }} actual
  753. */
  754. export function assertConversationTelemetryParity(expected, actual) {
  755. const result = compareConversationTelemetryParity(expected, actual);
  756. if (result.equal) return;
  757. throw new Error(
  758. `Conversation telemetry parity mismatch:\n${formatConversationTelemetryParityDifferences(result.differences)}`,
  759. );
  760. }
  761. /**
  762. * @typedef {object} ConversationTelemetryParityDiff
  763. * @property {"MISSING_EVENT" | "EXTRA_EVENT" | "MISSING_FIELD" | "EXTRA_FIELD" | "TYPE_MISMATCH" | "VALUE_MISMATCH" | "RELATION_MISMATCH" | "ORDER_MISMATCH" | "TIMING_INVARIANT_MISMATCH"} category
  764. * @property {"report" | "arms"} channel
  765. * @property {number | null} eventIndex
  766. * @property {string} path
  767. * @property {string} expected
  768. * @property {string} actual
  769. */
  770. /**
  771. * @typedef {object} ConversationTelemetryParityResult
  772. * @property {boolean} equal
  773. * @property {{ report: unknown[]; arms: unknown[] }} expected
  774. * @property {{ report: unknown[]; arms: unknown[] }} actual
  775. * @property {ConversationTelemetryParityDiff[]} differences
  776. */
  777. /**
  778. * @param {{ category: ConversationTelemetryParityDiff["category"]; channel: "report" | "arms"; eventIndex: number | null; path: string; expected: unknown; actual: unknown }} input
  779. * @returns {ConversationTelemetryParityDiff}
  780. */
  781. function createDiff(input) {
  782. return {
  783. ...input,
  784. expected: displayValue(input.expected),
  785. actual: displayValue(input.actual),
  786. };
  787. }
  788. /**
  789. * @param {ConversationTelemetryParityDiff} left
  790. * @param {ConversationTelemetryParityDiff} right
  791. */
  792. function compareDifferences(left, right) {
  793. return (
  794. (CATEGORY_ORDER.get(left.category) ?? 99) - (CATEGORY_ORDER.get(right.category) ?? 99) ||
  795. left.channel.localeCompare(right.channel) ||
  796. (left.eventIndex ?? -1) - (right.eventIndex ?? -1) ||
  797. left.path.localeCompare(right.path)
  798. );
  799. }
  800. /** @param {unknown} value */
  801. function displayValue(value) {
  802. if (value === MISSING_VALUE) return "<missing>";
  803. if (value === undefined) return "undefined";
  804. if (typeof value === "number" && Number.isNaN(value)) return "NaN";
  805. return stableJson(value);
  806. }
  807. /** @param {unknown} value */
  808. function stableJson(value) {
  809. if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
  810. if (isRecord(value)) {
  811. return `{${Object.keys(value)
  812. .sort()
  813. .map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`)
  814. .join(",")}}`;
  815. }
  816. const serialized = JSON.stringify(value);
  817. return serialized === undefined ? String(value) : serialized;
  818. }
  819. /** @param {unknown} value */
  820. function valueType(value) {
  821. if (value === null) return "null";
  822. if (Array.isArray(value)) return "array";
  823. return typeof value;
  824. }
  825. /** @param {unknown} value */
  826. /** @param {string} path @param {string} key */
  827. function appendPath(path, key) {
  828. return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key)
  829. ? `${path}.${key}`
  830. : `${path}[${JSON.stringify(key)}]`;
  831. }
  832. /** @param {unknown} value */
  833. function readNonEmptyString(value) {
  834. return typeof value === "string" && value.length > 0 ? value : null;
  835. }
  836. /** @param {readonly string[]} left @param {readonly string[]} right */
  837. function sameStringArray(left, right) {
  838. return left.length === right.length && left.every((value, index) => value === right[index]);
  839. }
  840. /** @param {unknown} value @returns {value is Record<string, unknown>} */
  841. function isRecord(value) {
  842. return typeof value === "object" && value !== null && !Array.isArray(value);
  843. }