otlp-exporter.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { context } from "@opentelemetry/api";
  2. import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
  3. import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
  4. import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
  5. import { CompressionAlgorithm } from "@opentelemetry/otlp-exporter-base";
  6. import { resourceFromAttributes } from "@opentelemetry/resources";
  7. import {
  8. AggregationTemporality,
  9. AggregationType,
  10. MeterProvider,
  11. PeriodicExportingMetricReader,
  12. type ViewOptions,
  13. } from "@opentelemetry/sdk-metrics";
  14. import {
  15. BasicTracerProvider,
  16. BatchSpanProcessor,
  17. ParentBasedSampler,
  18. TraceIdRatioBasedSampler,
  19. type Sampler,
  20. } from "@opentelemetry/sdk-trace-base";
  21. import {
  22. TELEMETRY_SCHEMA_VERSION,
  23. type AgentTelemetryRuntimeOwner,
  24. type TelemetryIdentitySnapshot,
  25. type TelemetryResourceContext,
  26. } from "@zcode/contracts/telemetry";
  27. import { AgentExecutionTelemetryRuntime } from "./agent-trace-runtime.js";
  28. import { OtelAgentTelemetryMetrics } from "./agent-metrics.js";
  29. import { ModelApiTelemetryStatusSink } from "./model-api-recorder.js";
  30. export const AGENT_METRIC_EXPORT_INTERVAL_MS = 300_000;
  31. export const AGENT_TRACE_SAMPLE_RATIO = 0.1;
  32. export interface CreateOwnedAgentTelemetryRuntimeOptions {
  33. endpoint: string;
  34. headers?: Record<string, string>;
  35. identity?: TelemetryIdentitySnapshot;
  36. maxBatchSize?: number;
  37. maxQueueSize?: number;
  38. metricEndpoint?: string;
  39. metricExportIntervalMs?: number;
  40. metricHeaders?: Record<string, string>;
  41. onWarning?: (message: string, context: Record<string, unknown>) => void;
  42. resource: TelemetryResourceContext;
  43. timeoutMs?: number;
  44. traceSampleRatio?: number;
  45. }
  46. /**
  47. * 该模块只由异步 Bootstrap 在 Telemetry 确认启用后动态加载。不要从公共入口静态导入,
  48. * 否则 `--help`、版本查询和 disabled 模式仍会承担 OTel SDK 初始化成本。
  49. */
  50. export function createOwnedAgentTelemetryRuntime(
  51. options: CreateOwnedAgentTelemetryRuntimeOptions,
  52. ): AgentTelemetryRuntimeOwner {
  53. const timeoutMs = options.timeoutMs ?? 3_000;
  54. const exporter = new OTLPTraceExporter({
  55. compression: CompressionAlgorithm.GZIP,
  56. headers: options.headers,
  57. timeoutMillis: timeoutMs,
  58. url: options.endpoint,
  59. });
  60. const processor = new BatchSpanProcessor(exporter, {
  61. exportTimeoutMillis: timeoutMs,
  62. maxExportBatchSize: options.maxBatchSize ?? 100,
  63. maxQueueSize: options.maxQueueSize ?? 2_000,
  64. scheduledDelayMillis: 5_000,
  65. });
  66. const traceResource = resourceFromAttributes(resourceAttributes(options.resource));
  67. const metricResource = resourceFromAttributes(metricResourceAttributes(options.resource));
  68. const provider = new BasicTracerProvider({
  69. forceFlushTimeoutMillis: timeoutMs,
  70. resource: traceResource,
  71. sampler: createAgentTraceSampler(options.traceSampleRatio),
  72. spanProcessors: [processor],
  73. });
  74. const metricExporter = new OTLPMetricExporter({
  75. compression: CompressionAlgorithm.GZIP,
  76. headers: options.metricHeaders ?? options.headers,
  77. // CLI Metric 不携带每进程实例 ID,必须用 DELTA 避免多个短生命周期生产者的累计
  78. // Counter/Histogram 在后端发生重置冲突。
  79. temporalityPreference: AggregationTemporality.DELTA,
  80. timeoutMillis: timeoutMs,
  81. url: options.metricEndpoint ?? options.endpoint,
  82. });
  83. const metricReader = new PeriodicExportingMetricReader({
  84. exporter: metricExporter,
  85. exportIntervalMillis: options.metricExportIntervalMs ?? AGENT_METRIC_EXPORT_INTERVAL_MS,
  86. exportTimeoutMillis: timeoutMs,
  87. });
  88. const meterProvider = new MeterProvider({
  89. readers: [metricReader],
  90. resource: metricResource,
  91. views: metricViews(),
  92. });
  93. const contextManager = new AsyncLocalStorageContextManager();
  94. const registered = context.setGlobalContextManager(contextManager.enable());
  95. if (!registered) {
  96. // 同进程宿主已注册 Context Manager 时复用宿主实例;未注册成功的本实例必须关闭,
  97. // 避免留下第二套 AsyncLocalStorage。
  98. contextManager.disable();
  99. }
  100. const tracer = provider.getTracer("@zcode/cli-agent-telemetry", String(TELEMETRY_SCHEMA_VERSION));
  101. const meter = meterProvider.getMeter(
  102. "@zcode/cli-agent-telemetry",
  103. String(TELEMETRY_SCHEMA_VERSION),
  104. );
  105. const metrics = new OtelAgentTelemetryMetrics(meter);
  106. const execution = new AgentExecutionTelemetryRuntime({
  107. identity: options.identity,
  108. metrics,
  109. onWarning: options.onWarning,
  110. tracer,
  111. });
  112. const statusSink = new ModelApiTelemetryStatusSink({
  113. modelExecution: execution,
  114. onWarning: options.onWarning,
  115. });
  116. let closed = false;
  117. return {
  118. abandonSession(sessionId) {
  119. execution.abandonSession(sessionId);
  120. statusSink.abandonSession(sessionId);
  121. },
  122. agentExecution: execution,
  123. enabled: true,
  124. modelExecution: execution,
  125. statusSink,
  126. async flush(flushOptions) {
  127. if (closed) return;
  128. await withTimeout(
  129. Promise.all([provider.forceFlush(), meterProvider.forceFlush()]),
  130. flushOptions?.timeoutMs ?? timeoutMs,
  131. );
  132. },
  133. async shutdown(shutdownOptions) {
  134. if (closed) return;
  135. closed = true;
  136. statusSink.shutdown();
  137. execution.abandonProcess();
  138. try {
  139. await withTimeout(
  140. Promise.all([provider.shutdown(), meterProvider.shutdown()]),
  141. shutdownOptions?.timeoutMs ?? timeoutMs,
  142. );
  143. } finally {
  144. if (registered) contextManager.disable();
  145. }
  146. },
  147. updateIdentity(snapshot) {
  148. execution.updateIdentity(snapshot);
  149. },
  150. };
  151. }
  152. export function createAgentTraceSampler(ratio = AGENT_TRACE_SAMPLE_RATIO): Sampler {
  153. return new ParentBasedSampler({
  154. root: new TraceIdRatioBasedSampler(ratio),
  155. });
  156. }
  157. export function metricViews(): ViewOptions[] {
  158. return [
  159. histogramView("zcode.agent.turn.duration", [1, 5, 10, 30, 60, 300, 600]),
  160. histogramView("zcode.model.*.duration", [0.25, 1, 2, 5, 10, 30, 60, 120]),
  161. histogramView(
  162. "zcode.context.compaction.duration",
  163. [0.01, 0.05, 0.1, 0.5, 1, 5, 30, 120, 300, 600],
  164. ),
  165. histogramView(
  166. "zcode.detached.operation.duration",
  167. [0.01, 0.05, 0.1, 0.5, 1, 5, 30, 120, 300, 600],
  168. ),
  169. histogramView("zcode.agent.step.duration", [0.01, 0.05, 0.1, 0.5, 1, 5, 30, 120, 300, 600]),
  170. histogramView("zcode.tool.execution.duration", [0.01, 0.1, 0.5, 1, 5, 30, 120, 300]),
  171. histogramView(
  172. "zcode.command.execution.duration",
  173. [0.01, 0.05, 0.1, 0.5, 1, 5, 30, 120, 300, 600],
  174. ),
  175. histogramView("zcode.*.time_to_first_*", [0.25, 0.5, 1, 2, 5, 10, 30, 60]),
  176. histogramView("zcode.model.call.attempts", [1, 2, 3, 5, 8]),
  177. cardinalityView("zcode.model.attempt.tokens"),
  178. cardinalityView("zcode.model.attempt.stream_stall.count"),
  179. cardinalityView("zcode.telemetry.creation_drop.count"),
  180. cardinalityView("zcode.telemetry.abandoned.count"),
  181. ];
  182. }
  183. function histogramView(instrumentName: string, boundaries: number[]): ViewOptions {
  184. return {
  185. aggregation: {
  186. options: { boundaries, recordMinMax: false },
  187. type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
  188. },
  189. aggregationCardinalityLimit: 250,
  190. instrumentName,
  191. };
  192. }
  193. function cardinalityView(instrumentName: string): ViewOptions {
  194. return {
  195. aggregationCardinalityLimit: 250,
  196. instrumentName,
  197. };
  198. }
  199. export function resourceAttributes(
  200. resource: TelemetryResourceContext,
  201. ): Record<string, string | number | boolean> {
  202. return telemetryResourceAttributes(resource, {
  203. includeInstallationId: true,
  204. includeServiceInstanceId: true,
  205. });
  206. }
  207. export function metricResourceAttributes(
  208. resource: TelemetryResourceContext,
  209. ): Record<string, string | number | boolean> {
  210. return telemetryResourceAttributes(resource, {
  211. includeInstallationId: false,
  212. includeServiceInstanceId: false,
  213. });
  214. }
  215. function telemetryResourceAttributes(
  216. resource: TelemetryResourceContext,
  217. options: {
  218. includeInstallationId: boolean;
  219. includeServiceInstanceId: boolean;
  220. },
  221. ): Record<string, string | number | boolean> {
  222. return compactResourceAttributes({
  223. "deployment.environment.name": resource.deploymentEnvironment,
  224. "host.arch": hostArchitecture(),
  225. "os.type": process.platform,
  226. "process.runtime.name": "nodejs",
  227. "process.runtime.version": process.version.replace(/^v/u, ""),
  228. // Metric Resource 也参与时序 Series 身份。CLI 每次启动生成的实例 ID 和安装 ID 只能
  229. // 属于 Trace;若进入 Metric,会在所有用户进程间制造无界基数。
  230. "service.instance.id": options.includeServiceInstanceId
  231. ? resource.serviceInstanceId
  232. : undefined,
  233. "service.name": resource.serviceName,
  234. "service.version": resource.cliVersion,
  235. "zcode.build.commit_id": resource.buildCommitId,
  236. "zcode.device.installation_id": options.includeInstallationId
  237. ? resource.installationId
  238. : undefined,
  239. "zcode.product.version": resource.productVersion,
  240. "zcode.runtime.distribution": resource.runtimeDistribution,
  241. "zcode.runtime.surface": resource.runtimeSurface,
  242. "zcode.telemetry.schema_owner": "cli",
  243. "zcode.telemetry.schema_version": TELEMETRY_SCHEMA_VERSION,
  244. });
  245. }
  246. function hostArchitecture(): string {
  247. switch (process.arch) {
  248. case "x64":
  249. return "amd64";
  250. case "ia32":
  251. return "x86";
  252. default:
  253. return process.arch;
  254. }
  255. }
  256. function compactResourceAttributes(
  257. attributes: Record<string, string | number | boolean | undefined>,
  258. ): Record<string, string | number | boolean> {
  259. const compacted: Record<string, string | number | boolean> = {};
  260. for (const [key, value] of Object.entries(attributes)) {
  261. if (value !== undefined && value !== "") compacted[key] = value;
  262. }
  263. return compacted;
  264. }
  265. async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
  266. let timeout: number | undefined;
  267. try {
  268. return await Promise.race([
  269. promise,
  270. new Promise<undefined>((resolve) => {
  271. timeout = setTimeout(resolve, Math.max(1, timeoutMs));
  272. }),
  273. ]);
  274. } finally {
  275. if (timeout) clearTimeout(timeout);
  276. }
  277. }