otlp-integration.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { createServer } from "node:http";
  2. import { gunzipSync } from "node:zlib";
  3. import { opentelemetry } from "@opentelemetry/otlp-transformer/build/src/generated/root.js";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { createOwnedAgentTelemetryRuntime } from "../src/otlp-exporter.js";
  6. let closeOwner: (() => Promise<void>) | undefined;
  7. afterEach(async () => {
  8. await closeOwner?.();
  9. closeOwner = undefined;
  10. });
  11. describe("ARMS-compatible OTLP/HTTP V4", () => {
  12. it("gzip 批量上报真实 Trace,并携带三条独立版本轴和写入 Header", async () => {
  13. const requests: Array<{
  14. body: Buffer;
  15. headers: Record<string, string | string[] | undefined>;
  16. url: string;
  17. }> = [];
  18. const server = createServer((request, response) => {
  19. const chunks: Buffer[] = [];
  20. request.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
  21. request.on("end", () => {
  22. requests.push({
  23. body: Buffer.concat(chunks),
  24. headers: request.headers,
  25. url: request.url ?? "",
  26. });
  27. response.writeHead(200);
  28. response.end();
  29. });
  30. });
  31. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  32. const address = server.address();
  33. if (!address || typeof address === "string") throw new Error("Missing server address");
  34. const owner = createOwnedAgentTelemetryRuntime({
  35. endpoint: `http://127.0.0.1:${address.port}/v1/traces`,
  36. headers: { "x-arms-license-key": "write-only-test" },
  37. metricEndpoint: `http://127.0.0.1:${address.port}/v1/metrics`,
  38. // 集成测试需要稳定拿到完整 Trace;生产默认采样率由独立配置测试覆盖。
  39. traceSampleRatio: 1,
  40. resource: {
  41. buildCommitId: "abcdef1234567",
  42. cliVersion: "0.16.1",
  43. installationId: "installation-1",
  44. productVersion: "3.6.1",
  45. runtimeDistribution: "packaged",
  46. runtimeSurface: "desktop_local_host",
  47. serviceInstanceId: "instance-1",
  48. serviceName: "zcode-cli-agent",
  49. },
  50. });
  51. closeOwner = async () => {
  52. await owner.shutdown();
  53. await new Promise<void>((resolve, reject) =>
  54. server.close((error) => (error ? reject(error) : resolve())),
  55. );
  56. };
  57. const turn = owner.agentExecution.startTurn({
  58. context: {
  59. actorKind: "main",
  60. launchSurface: "desktop",
  61. sessionId: "session-1",
  62. turnId: "turn-1",
  63. },
  64. turnNumber: 1,
  65. });
  66. await turn.run(async () => {
  67. const step = owner.agentExecution.startStep({ stepId: "step-1", stepIndex: 0 });
  68. await step.run(async () => {
  69. const call = owner.modelExecution.startCall({
  70. logicalCallId: "logical-1",
  71. operation: "agent_step",
  72. requested: {
  73. providerId: "anthropic-prod",
  74. reasoning: {
  75. capability: "supported",
  76. effectiveControl: "fixed_level",
  77. effectiveState: "enabled",
  78. requestedControl: "fixed_level",
  79. requestedState: "enabled",
  80. },
  81. requestedModel: "claude-test",
  82. },
  83. streaming: true,
  84. });
  85. await call.run(async () => {
  86. const attempt = call.startAttempt({
  87. apiOperation: "messages",
  88. attemptCause: "initial",
  89. attemptNumber: 1,
  90. requestId: "request-1",
  91. target: {
  92. providerId: "anthropic-prod",
  93. providerKind: "anthropic",
  94. reasoning: {
  95. capability: "supported",
  96. effectiveControl: "fixed_level",
  97. effectiveState: "enabled",
  98. requestedControl: "fixed_level",
  99. requestedState: "enabled",
  100. },
  101. requestedModel: "claude-test",
  102. },
  103. transport: "sse",
  104. });
  105. await attempt.run(async () => {
  106. attempt.markFirstContent();
  107. attempt.setInputTokens(12);
  108. attempt.setOutputTokens(4);
  109. attempt.finishCompleted();
  110. });
  111. call.finishCompleted();
  112. });
  113. step.finishCompleted("model_completed");
  114. });
  115. turn.finishCompleted("assistant_message");
  116. });
  117. await owner.flush({ timeoutMs: 3_000 });
  118. expect(requests).toHaveLength(2);
  119. const traceRequest = requests.find((request) => request.url === "/v1/traces");
  120. const metricRequest = requests.find((request) => request.url === "/v1/metrics");
  121. expect(traceRequest?.headers["x-arms-license-key"]).toBe("write-only-test");
  122. expect(traceRequest?.headers["content-encoding"]).toBe("gzip");
  123. const decoded = opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.decode(
  124. gunzipSync(traceRequest!.body),
  125. );
  126. const resource = decoded.resourceSpans[0]?.resource?.attributes ?? [];
  127. const attributes = Object.fromEntries(
  128. resource.map((attribute) => [
  129. attribute.key,
  130. attribute.value?.stringValue ??
  131. (attribute.value?.intValue !== undefined
  132. ? Number(attribute.value.intValue)
  133. : undefined) ??
  134. attribute.value?.boolValue,
  135. ]),
  136. );
  137. expect(attributes).toMatchObject({
  138. "service.name": "zcode-cli-agent",
  139. "service.version": "0.16.1",
  140. "zcode.device.installation_id": "installation-1",
  141. "zcode.product.version": "3.6.1",
  142. "zcode.telemetry.schema_owner": "cli",
  143. "zcode.telemetry.schema_version": 6,
  144. });
  145. const spanNames = decoded.resourceSpans
  146. .flatMap((item) => item.scopeSpans)
  147. .flatMap((item) => item.spans)
  148. .map((item) => item.name);
  149. expect(spanNames).toEqual(expect.arrayContaining(["agent_turn", "agent_step"]));
  150. expect(metricRequest?.headers["x-arms-license-key"]).toBe("write-only-test");
  151. expect(metricRequest?.headers["content-encoding"]).toBe("gzip");
  152. const decodedMetrics =
  153. opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.decode(
  154. gunzipSync(metricRequest!.body),
  155. );
  156. const metricResource = decodedMetrics.resourceMetrics[0]?.resource?.attributes ?? [];
  157. const metricResourceAttributes = Object.fromEntries(
  158. metricResource.map((attribute) => [
  159. attribute.key,
  160. attribute.value?.stringValue ??
  161. (attribute.value?.intValue !== undefined
  162. ? Number(attribute.value.intValue)
  163. : undefined) ??
  164. attribute.value?.boolValue,
  165. ]),
  166. );
  167. expect(metricResourceAttributes).toMatchObject({
  168. "service.name": "zcode-cli-agent",
  169. "service.version": "0.16.1",
  170. "zcode.product.version": "3.6.1",
  171. "zcode.telemetry.schema_version": 6,
  172. });
  173. expect(metricResourceAttributes["zcode.device.installation_id"]).toBeUndefined();
  174. expect(metricResourceAttributes["service.instance.id"]).toBeUndefined();
  175. const metricNames = decodedMetrics.resourceMetrics
  176. .flatMap((item) => item.scopeMetrics)
  177. .flatMap((item) => item.metrics)
  178. .map((item) => item.name);
  179. expect(metricNames).toEqual(
  180. expect.arrayContaining([
  181. "zcode.agent.turn.duration",
  182. "zcode.agent.step.duration",
  183. "zcode.model.attempt.duration",
  184. "zcode.model.attempt.time_to_first_content",
  185. "zcode.model.attempt.tokens",
  186. "zcode.model.call.attempts",
  187. "zcode.model.call.duration",
  188. ]),
  189. );
  190. const metricAttributeKeys = decodedMetrics.resourceMetrics
  191. .flatMap((item) => item.scopeMetrics)
  192. .flatMap((item) => item.metrics)
  193. .flatMap((metric) => [
  194. ...(metric.gauge?.dataPoints ?? []),
  195. ...(metric.histogram?.dataPoints ?? []),
  196. ...(metric.sum?.dataPoints ?? []),
  197. ])
  198. .flatMap((point) => point.attributes.map((attribute) => attribute.key));
  199. expect(metricAttributeKeys).not.toEqual(
  200. expect.arrayContaining([
  201. "zcode.device.installation_id",
  202. "zcode.execution.session_id",
  203. "zcode.execution.turn_id",
  204. "zcode.model_attempt.request_id",
  205. ]),
  206. );
  207. });
  208. it("Trace 未采样时仍完整导出 Metric", async () => {
  209. const requestUrls: string[] = [];
  210. const server = createServer((request, response) => {
  211. request.on("data", () => undefined);
  212. request.on("end", () => {
  213. requestUrls.push(request.url ?? "");
  214. response.writeHead(200);
  215. response.end();
  216. });
  217. });
  218. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  219. const address = server.address();
  220. if (!address || typeof address === "string") throw new Error("Missing server address");
  221. const owner = createOwnedAgentTelemetryRuntime({
  222. endpoint: `http://127.0.0.1:${address.port}/v1/traces`,
  223. metricEndpoint: `http://127.0.0.1:${address.port}/v1/metrics`,
  224. resource: {
  225. cliVersion: "0.16.1",
  226. productVersion: "3.6.1",
  227. runtimeDistribution: "packaged",
  228. runtimeSurface: "desktop_local_host",
  229. serviceInstanceId: "instance-unsampled",
  230. serviceName: "zcode-cli-agent",
  231. },
  232. traceSampleRatio: 0,
  233. });
  234. closeOwner = async () => {
  235. await owner.shutdown();
  236. await new Promise<void>((resolve, reject) =>
  237. server.close((error) => (error ? reject(error) : resolve())),
  238. );
  239. };
  240. const turn = owner.agentExecution.startTurn({
  241. context: {
  242. actorKind: "main",
  243. launchSurface: "desktop",
  244. sessionId: "session-unsampled",
  245. turnId: "turn-unsampled",
  246. },
  247. turnNumber: 1,
  248. });
  249. turn.finishCompleted("assistant_message");
  250. await owner.flush({ timeoutMs: 3_000 });
  251. expect(requestUrls).toEqual(["/v1/metrics"]);
  252. });
  253. });