← Back to Pull requests

feat(telemetry): add opt-in OTLP usage traces #4821

Closed
seekskyworld closed this pull request without merging on Nov 29, 2026 05:22 UTC
View on GitHub
seekskyworld seekskyworld commented on Sep 05, 2026 02:45 UTC
Author

Updated 2026-11-28: this is a legacy TypeScript contribution targeting 0.2.x. Main was replaced by the Rust implementation in #7157. The unchanged head merges cleanly with 0.2.x at 4daab16b1; earlier validation below applies to that TypeScript implementation, not Rust main. Retargeting alone is not a new successful CI run. Automated metadata update by OpenAI Codex under the contributor's direction.

Summary

Fixes #3757.

Add opt-in OTLP/HTTP usage spans for canonical physical model attempts, legacy auxiliary calls and tool invocations. Canonical attempts export after the Usage projection commits, without adding a second send-level meter. Repeated catch-up and reopening do not re-export existing rows; unpriced cost and missing usage remain absent, with their basis attached. Previously projected history is not backfilled.

Exports omit request evidence, prompts, tool arguments/results, credentials and Session paths. Arbitrary error names use a fixed allowlist. Trace-specific endpoint/header/timeout variables override generic variables when nonempty. Retryable failures use bounded backoff; repeated failures log once until recovery.

Each request contains at most 32 spans, with at most 1,024 pending spans plus one in-flight batch. Overflow drops new optional exports while preserving the local ledger. All concurrent flush callers join the complete drain, and close cancels outstanding work after one second. This is best-effort delivery: overflow, timeout or a crash after local commit can lose exports; it is not a durable network outbox.

Verification

Updated on 2026-11-12 at 5943934, merged with TypeScript main at 3f2d17cda:

  • Complete Storage suite: 1,759 passed, 8 platform skips, zero failures.

  • Node 22.19.0: 75 exporter/Usage/ledger tests passed. These cover canonical file-backed attempts reaching a local HTTP collector, replay/reopen deduplication, rollback/retry, missing usage/unpriced cost and evidence omission, bounded batching and a stalled child-process shutdown.

  • The complete WorkHub remote-bridge test file passes 22/22, including the clearing-receipt case from the older failed hosted run. The inherited test and production bridge are unchanged by this PR; one local pass does not establish that its intermittent close race is eliminated.

  • Clean full repository rebuild, typecheck, lint, format, Desktop/UI knip, ASF headers and diff checks pass on Node 24.18.1.

  • Earlier fault-injection evidence for canonical exports, shutdown bounds and batch limits remains in the review history. No live third-party collector or full native Desktop E2E run was used.
  • Hosted check

    Previous run 38226323772 failed in the unchanged WorkHub bridge test with WorkHub remote transport is inactive; review reproduced the inherited close race on both that head and its main baseline. The updated head has been pushed for fresh CI. Local passing results are not presented as a green hosted gate.

    AI use

  • No generative tool made a substantive contribution

  • Generative tooling made a substantive contribution
  • Tool(s) and scope: OpenAI Codex authored the exporter, tests, documentation, and PR description for @seekskyworld. Human review and merge remain with the maintainers.

    Checklist

  • Tests cover the change and fail without it

  • Lint, format, typecheck and the affected suites pass locally
  • Does this PR entail a change in behavior?

  • Yes — described under Summary above

  • No
  • Diff: 1454 lines (+1447 / -7) across 8 files Reviewer: Astro-Han Review duration: 122556m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.58) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.58 · 1454 lines diff across 8 files
    0.58
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.75 · 5 substantive comment(s)
    0.75
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    31 items
    Astro-Han Astro-Han commented on Sep 05, 2026 15:57 UTC
    Reviewer

    Reviewed current head d193c6843dc779b0ec996bcdace8ef0232f839b3 (OPEN). Three P2s plus three P3s below, no P0/P1. Default-off is done right; the problems all sit behind the opt-in — new network paths that do not reuse this repo's existing safeguards. This is a new feature with a new outbound path, so it needs a human decision regardless.

    P2 — insert is double-wrapped in a lease; every model/tool call re-reads the root marker file

    recordLlmCall/recordToolInvocation now wrap in an extra run(...) inside admitSessionUsageMutation, which already runs once (usage-stores.ts:385) — run(run(insert)). Not a deadlock (beginOperation at root-authority.ts:738 is ref-counted, reentrant), but every runWithStorageRootLease awaits assertRootIdentity → confirmRootSnapshot → readAndValidateRootMarker (:1055-1069), a disk read plus validation — on the two hottest telemetry paths. And it is unrelated to adding an exporter. Fix: drop the inner run; the outer admission already guarantees lease context.

    P2 — outbound request headers unvalidated while a hardened helper already exists

    parseHeaders (otlp-telemetry-exporter.ts) splits OTEL_EXPORTER_OTLP_HEADERS and stuffs them into fetch headers verbatim: no name-charset check, no control-character rejection, no protected-header denylist — while packages/core/src/request-customization.ts already has the HEADER_NAME regex and PROTECTED_HEADERS set (authorization/host/content-length/…). Threat model note: these come from the operator's own env, not a remote attacker — but env may come from someone else's shell profile or CI config. Concretely: user headers spread after 'content-type': 'application/json', so a user header can override content-type while the body stays JSON — silently undecodable at the collector and painful to debug. Minimum: reject control characters and refuse to override content-type.

    P2 — credentials allowed over plaintext http with no warning

    resolveEndpoint accepts anything new URL() parses, scheme unrestricted — so http://… plus the README's own authorization=Bearer%20token example sends the token and all telemetry in cleartext. Do not ban http (LAN collectors legitimately use it), but warn once on the "non-https + authorization header" combination; the README example shows exactly this pairing and will be copy-pasted.

    P2 — README claims "bounded error classes" that neither types nor code guarantee

    errorClass is errorClass?: string (usage-stats/types.ts:131) — a free string. Most producers use constants, but at least one reads from an event: session-projection-helpers.ts:172 returns event.reason ?? event.code ?? 'unknown', and whether event.reason is bounded was not traced to the root — so leakage cannot be asserted, but neither can its absence. An export boundary promise ("never exported") should be enforced at the boundary, not by upstream discipline: allowlist or length-truncate errorClass in exportLlmCall/exportToolInvocation.

    P3s (non-blocking)

  • Nanosecond timestamps exceed double-precision range: startedAt (~1.77e12 ms) × 1e6 ≈ 1.77e18 > MAX_SAFE_INTEGER — the last digits of startTimeUnixNano are rounding artifacts, not real values.

  • Each span is its own trace, so these are events, not traces — name/shape expectations should say so.

  • A dead collector logs one console.error per second with no backoff or kill-switch.
  • Checked and found sound

    Attribute set matches the README promise (no prompts, contents, args/results, paths); default-off; per-principal quota logic untouched.

    What I could not judge

    No collector was started and the export path was not run end-to-end; all conclusions are from code. Whether event.reason can carry free text was not traced to the root — someone familiar with runtime event sources should confirm, since it decides whether the README sentence can stay.

    ---

    Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

    <details><summary>简体中文</summary>

    本条结论全部来自 @Opus-Qronos-AstroHan 的审查。我自己没有读这份 diff;我核的是当前 head 有没有漂移。当前 head 是 d193c684,未关闭。默认关闭做对了,三条 P2 都在打开之后:双层 lease 多读文件、出网头没校验、明文 http 不提醒、错误类别无界,另有三条小的提醒。新功能加出网,按规矩要人类拍板。

    </details>

    seekskyworld seekskyworld commented on Sep 07, 2026 04:06 UTC
    Author

    Addressed the review items in commit 6080c4fc4:

  • Removed the nested storage-root lease around insertLlmCall and insertToolInvocation; the admission lease now covers the durable write and exporter enqueue directly.

  • Hardened OTEL_EXPORTER_OTLP_HEADERS: token grammar and size limits, duplicate-name rejection, control-character rejection, and protected transport headers (including content-type) are enforced. authorization remains supported for collectors.

  • Added a one-time-per-configured-endpoint warning when authorization is sent to a non-HTTPS endpoint; HTTP remains allowed for local/LAN collectors.

  • Bounded exported errorClass values at the OTLP boundary to 128 Unicode characters and removed control characters.

  • Switched Unix-nanosecond conversion to integer BigInt arithmetic and documented the independent-event semantics.
  • Validation: @maka/storage build/typecheck, 1,134 storage tests (1,126 passed, 8 platform skips), OTLP focused tests (6/6), Biome, ASF header audit, and git diff --check all pass. The backoff/kill-switch suggestion remains a separate non-blocking follow-up because it changes exporter delivery policy.

    hqhq1025 hqhq1025 commented on code on Sep 08, 2026 11:37 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {

    [P1] Bound each export request before joining it into shutdown. This fetch has no AbortSignal and the exporter ignores both OTLP timeout variables. I reproduced this through the real file-backed Usage writer with a local HTTP server that accepted the request but never returned headers: stores.close() was still pending after 750 ms and completed only after the socket was destroyed. usage-stores.ts:447-452 awaits this close, the Runtime Host composition awaits storage close, and the Host then reaches its 10-second forced-termination deadline, skipping the rest of graceful cleanup. Please add a finite request timeout/cancellation path, honor the signal-specific/generic timeout configuration as appropriate, and ensure close() cannot wait past the Host shutdown budget.

    hqhq1025 hqhq1025 commented on code on Sep 08, 2026 11:37 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json', ...this.#headers },
    +        body: JSON.stringify({
    +          resourceSpans: [
    +            {
    +              resource: { attributes: this.#resourceAttributes },
    +              scopeSpans: [{ scope: { name: 'maka.storage' }, spans }],
    +            },
    +          ],
    +        }),
    +      });
    +      if (!response.ok) {
    +        console.error(`[telemetry] OTLP export failed: HTTP ${response.status}`);
    +      }
    +    } catch {
    +      console.error('[telemetry] OTLP export failed: request error');
    +    }
    +  }
    +}
    +
    +function toSpan(input: {
    +  name: string;
    +  startedAt: number;
    +  durationMs: number;
    +  status: PersistedLlmCallRecord['status'];
    +  attributes: OtlpAttribute[];
    +}): OtlpSpan {
    +  const traceId = randomUUID().replaceAll('-', '');
    +  const startedAt = normalizeTimestamp(input.startedAt);
    +  const endedAt = normalizeTimestamp(input.startedAt + Math.max(0, input.durationMs));
    +  return {
    +    traceId,
    +    spanId: traceId.slice(0, 16),
    +    name: input.name,
    +    kind: 1,
    +    startTimeUnixNano: unixNanoseconds(startedAt),
    +    endTimeUnixNano: unixNanoseconds(endedAt),
    +    attributes: input.attributes,
    +    status: { code: input.status === 'success' ? 1 : input.status === 'error' ? 2 : 0 },
    +  };
    +}
    +
    +function stringAttribute(key: string, value: string): OtlpAttribute {
    +  return { key, value: { stringValue: value } };
    +}
    +
    +function numberAttribute(key: string, value: number): OtlpAttribute {
    +  return { key, value: { doubleValue: value } };
    +}
    +
    +function resolveEndpoint(env: Environment): string | undefined {
    +  const configured = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
    +  if (!configured) return undefined;
    +  try {
    +    const url = new URL(configured);
    +    const pathname = url.pathname.replace(/\/+$/u, '');
    +    url.pathname = pathname.endsWith('/v1/traces') ? pathname : `${pathname}/v1/traces`;

    [P2] Do not append /v1/traces to OTEL_EXPORTER_OTLP_TRACES_ENDPOINT. The OTLP exporter specification requires a per-signal endpoint to be used as-is; only OTEL_EXPORTER_OTLP_ENDPOINT is a base URL that gets the signal path appended. On this head, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://collector.example/custom/traces sent to https://collector.example/custom/traces/v1/traces, so valid collectors with a custom trace route receive nothing. The current test covers only a URL that already ends in /v1/traces, which masks the branch. Resolve the two variables separately and add custom-path/root-path cases.

    hqhq1025 hqhq1025 commented on code on Sep 08, 2026 11:37 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);

    [P2] Honor OTEL_EXPORTER_OTLP_TRACES_HEADERS before the generic header variable. It is the standard per-signal override, but this reads only OTEL_EXPORTER_OTLP_HEADERS. A probe with a trace endpoint plus OTEL_EXPORTER_OTLP_TRACES_HEADERS=authorization=Bearer%20trace-token produced a request with no authorization header, so a standards-compliant authenticated configuration silently drops every export. Parse the trace-specific value when present and fall back to the generic value otherwise, with the same validation.

    hqhq1025 hqhq1025 commented on code on Sep 08, 2026 11:37 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json', ...this.#headers },
    +        body: JSON.stringify({
    +          resourceSpans: [
    +            {
    +              resource: { attributes: this.#resourceAttributes },
    +              scopeSpans: [{ scope: { name: 'maka.storage' }, spans }],
    +            },
    +          ],
    +        }),
    +      });
    +      if (!response.ok) {
    +        console.error(`[telemetry] OTLP export failed: HTTP ${response.status}`);
    +      }
    +    } catch {
    +      console.error('[telemetry] OTLP export failed: request error');
    +    }
    +  }
    +}
    +
    +function toSpan(input: {
    +  name: string;
    +  startedAt: number;
    +  durationMs: number;
    +  status: PersistedLlmCallRecord['status'];
    +  attributes: OtlpAttribute[];
    +}): OtlpSpan {
    +  const traceId = randomUUID().replaceAll('-', '');
    +  const startedAt = normalizeTimestamp(input.startedAt);
    +  const endedAt = normalizeTimestamp(input.startedAt + Math.max(0, input.durationMs));
    +  return {
    +    traceId,
    +    spanId: traceId.slice(0, 16),
    +    name: input.name,
    +    kind: 1,
    +    startTimeUnixNano: unixNanoseconds(startedAt),
    +    endTimeUnixNano: unixNanoseconds(endedAt),
    +    attributes: input.attributes,
    +    status: { code: input.status === 'success' ? 1 : input.status === 'error' ? 2 : 0 },
    +  };
    +}
    +
    +function stringAttribute(key: string, value: string): OtlpAttribute {
    +  return { key, value: { stringValue: value } };
    +}
    +
    +function numberAttribute(key: string, value: number): OtlpAttribute {
    +  return { key, value: { doubleValue: value } };
    +}
    +
    +function resolveEndpoint(env: Environment): string | undefined {
    +  const configured = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
    +  if (!configured) return undefined;
    +  try {
    +    const url = new URL(configured);
    +    const pathname = url.pathname.replace(/\/+$/u, '');
    +    url.pathname = pathname.endsWith('/v1/traces') ? pathname : `${pathname}/v1/traces`;
    +    return url.toString();
    +  } catch {
    +    return undefined;
    +  }
    +}
    +
    +function parseHeaders(value: string | undefined): Record<string, string> {
    +  if (!value) return {};
    +  const headers = Object.create(null) as Record<string, string>;
    +  const names = new Set<string>();
    +  let encodedBytes = 0;
    +  for (const item of value.split(',')) {
    +    const separator = item.indexOf('=');
    +    if (separator <= 0) continue;
    +    const key = item.slice(0, separator).trim();
    +    const raw = item.slice(separator + 1).trim();
    +    if (
    +      !key ||
    +      key.length > MAX_HEADER_NAME_LENGTH ||
    +      !HEADER_NAME.test(key) ||
    +      PROTECTED_HEADERS.has(key.toLowerCase())
    +    ) {
    +      continue;
    +    }
    +    const lowerKey = key.toLowerCase();
    +    if (names.has(lowerKey) || names.size >= MAX_HEADER_COUNT) continue;
    +    const decoded = decodeValue(raw);
    +    if (
    +      !raw ||
    +      decoded.length > MAX_HEADER_VALUE_LENGTH ||
    +      /[^\t\u0020-\u007e\u0080-\u00ff]/u.test(decoded)
    +    ) {
    +      continue;
    +    }
    +    const entryBytes = new TextEncoder().encode(`${key}:${decoded}`).byteLength;
    +    if (encodedBytes + entryBytes > MAX_HEADER_BYTES) break;
    +    encodedBytes += entryBytes;
    +    names.add(lowerKey);
    +    headers[key] = decoded;
    +  }
    +  return headers;
    +}
    +
    +function warnForInsecureAuthorization(endpoint: string, headers: Record<string, string>): void {
    +  let url: URL;
    +  try {
    +    url = new URL(endpoint);
    +  } catch {
    +    return;
    +  }
    +  if (url.protocol === 'https:') return;
    +  const hasAuthorization = Object.keys(headers).some(
    +    (name) => name.toLowerCase() === 'authorization',
    +  );
    +  if (hasAuthorization && !insecureAuthorizationWarnings.has(endpoint)) {
    +    insecureAuthorizationWarnings.add(endpoint);
    +    console.warn(
    +      '[telemetry] OTLP endpoint is not using HTTPS while an authorization header is configured; credentials and telemetry will be sent without transport encryption',
    +    );
    +  }
    +}
    +
    +function boundedErrorClass(value: string | undefined): string | undefined {
    +  if (!value) return undefined;
    +  const sanitized = value.trim().replace(/[\u0000-\u001f\u007f-\u009f]/gu, '');

    [P2] Truncation does not enforce the documented promise that credentials are never exported. The production tool failure path uses classifyError(err), whose fallback preserves an arbitrary Error.name; with error.name = 'sk-live-secret-value', the resulting errorClass was exported verbatim as maka.error.class. The public Usage record type is also an unrestricted string. Please project this field onto an allowlist of known classes (or redact credential-shaped values) at this outbound boundary rather than relying on length/control-character filtering.

    hqhq1025 hqhq1025 commented on code on Sep 08, 2026 11:37 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json', ...this.#headers },
    +        body: JSON.stringify({
    +          resourceSpans: [
    +            {
    +              resource: { attributes: this.#resourceAttributes },
    +              scopeSpans: [{ scope: { name: 'maka.storage' }, spans }],
    +            },
    +          ],
    +        }),
    +      });
    +      if (!response.ok) {
    +        console.error(`[telemetry] OTLP export failed: HTTP ${response.status}`);

    [P3] Suppress or back off repeated collector failures. With a continuing one-record-per-second workload and a collector returning 503, two consecutive batches produced two identical console.error lines; this continues once per flush interval while the collector is down. In the CLI/TUI process that can continuously pollute stderr. Log once until recovery or apply bounded exponential backoff.

    hqhq1025 hqhq1025 commented on Sep 08, 2026 11:37 UTC
    Reviewer

    Reviewed current head 6080c4fc42312be706aa0f314c952524506cb9b6. The follow-up fixes the prior nested storage lease, unsafe/protected generic headers, plaintext authorization warning, nanosecond precision, error-class length bound, and trace-semantics documentation. One P1, three P2s, and one P3 remain below, so this is not technically ready. Because this is a new opt-in outbound telemetry path, the final merge decision also remains with a human maintainer.

    Validation on this exact head: clean install; build:test; full typecheck; Storage 1124 passed / 10 skipped; focused exporter 6/6; full lint and format; ASF headers; git diff --check; hosted test green; clean merge-tree against current main 42fa4d070504e672173c46dd75f7fcabb88789f5.

    Production-path probes reproduced the material failures: a real file-backed Usage writer accepted one record and then stayed pending in close() after 750 ms when a local collector accepted the request without responding; a custom traces endpoint was rewritten to a different URL and trace-specific auth headers were omitted; and Runtime's production classifyError can preserve an arbitrary Error.name, which the exporter sends unchanged apart from truncation.

    The previous P3 about repeated failure logging also remains: two failed one-second batches emitted two console.error lines. No external collector or non-Linux shutdown path was exercised.

    <details><summary>简体中文</summary>

    当前 head 修复了旧审查中的双层 lease、通用请求头校验、明文授权警告、纳秒精度和独立事件说明。但仍有一条关闭路径 P1、三条标准配置/隐私边界 P2,以及一条持续失败刷日志的 P3,因此技术结论仍是 NO-GO。完整 Storage、构建、类型检查、lint、format、ASF、当前 main 合并树和 hosted test 均通过;缺陷来自真实本地 collector 与生产存储 writer 探针,不是测试失败推断。

    </details>

    Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 15:39 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {

    Addressed in f9d793381. Each request receives an AbortSignal and a finite timeout; the trace-specific timeout overrides the generic timeout. Closing shares a separate 1-second cancellation grace across in-flight and pending batches, even for a 60-second configured request timeout. A real never-responding HTTP collector test drives the file-backed Usage writer and proves stores.close() settles; it fails with the old exporter. Cancellation also bounds a transport that ignores its signal. Storage 1,132 passed / 8 skipped; focused exporter and Usage tests 30/30.

    Automated follow-up by OpenAI Codex for @seekskyworld.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 15:39 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json', ...this.#headers },
    +        body: JSON.stringify({
    +          resourceSpans: [
    +            {
    +              resource: { attributes: this.#resourceAttributes },
    +              scopeSpans: [{ scope: { name: 'maka.storage' }, spans }],
    +            },
    +          ],
    +        }),
    +      });
    +      if (!response.ok) {
    +        console.error(`[telemetry] OTLP export failed: HTTP ${response.status}`);
    +      }
    +    } catch {
    +      console.error('[telemetry] OTLP export failed: request error');
    +    }
    +  }
    +}
    +
    +function toSpan(input: {
    +  name: string;
    +  startedAt: number;
    +  durationMs: number;
    +  status: PersistedLlmCallRecord['status'];
    +  attributes: OtlpAttribute[];
    +}): OtlpSpan {
    +  const traceId = randomUUID().replaceAll('-', '');
    +  const startedAt = normalizeTimestamp(input.startedAt);
    +  const endedAt = normalizeTimestamp(input.startedAt + Math.max(0, input.durationMs));
    +  return {
    +    traceId,
    +    spanId: traceId.slice(0, 16),
    +    name: input.name,
    +    kind: 1,
    +    startTimeUnixNano: unixNanoseconds(startedAt),
    +    endTimeUnixNano: unixNanoseconds(endedAt),
    +    attributes: input.attributes,
    +    status: { code: input.status === 'success' ? 1 : input.status === 'error' ? 2 : 0 },
    +  };
    +}
    +
    +function stringAttribute(key: string, value: string): OtlpAttribute {
    +  return { key, value: { stringValue: value } };
    +}
    +
    +function numberAttribute(key: string, value: number): OtlpAttribute {
    +  return { key, value: { doubleValue: value } };
    +}
    +
    +function resolveEndpoint(env: Environment): string | undefined {
    +  const configured = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
    +  if (!configured) return undefined;
    +  try {
    +    const url = new URL(configured);
    +    const pathname = url.pathname.replace(/\/+$/u, '');
    +    url.pathname = pathname.endsWith('/v1/traces') ? pathname : `${pathname}/v1/traces`;

    Addressed in f9d793381. Trace-specific endpoints are now used as-is, preserving custom paths, query strings, root paths and trailing slashes. Only the generic base endpoint gets /v1/traces appended. Updated the old trailing-slash expectation and added independent custom/root/generic-path cases; the old implementation fails them.

    Automated follow-up by OpenAI Codex for @seekskyworld.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 15:39 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);

    Addressed in f9d793381. OTEL_EXPORTER_OTLP_TRACES_HEADERS now overrides OTEL_EXPORTER_OTLP_HEADERS, including an explicit empty override. Tests cover authenticated trace headers, generic fallback, empty override, protected content-type and rejected control characters using the same parser.

    Automated follow-up by OpenAI Codex for @seekskyworld.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 15:39 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json', ...this.#headers },
    +        body: JSON.stringify({
    +          resourceSpans: [
    +            {
    +              resource: { attributes: this.#resourceAttributes },
    +              scopeSpans: [{ scope: { name: 'maka.storage' }, spans }],
    +            },
    +          ],
    +        }),
    +      });
    +      if (!response.ok) {
    +        console.error(`[telemetry] OTLP export failed: HTTP ${response.status}`);
    +      }
    +    } catch {
    +      console.error('[telemetry] OTLP export failed: request error');
    +    }
    +  }
    +}
    +
    +function toSpan(input: {
    +  name: string;
    +  startedAt: number;
    +  durationMs: number;
    +  status: PersistedLlmCallRecord['status'];
    +  attributes: OtlpAttribute[];
    +}): OtlpSpan {
    +  const traceId = randomUUID().replaceAll('-', '');
    +  const startedAt = normalizeTimestamp(input.startedAt);
    +  const endedAt = normalizeTimestamp(input.startedAt + Math.max(0, input.durationMs));
    +  return {
    +    traceId,
    +    spanId: traceId.slice(0, 16),
    +    name: input.name,
    +    kind: 1,
    +    startTimeUnixNano: unixNanoseconds(startedAt),
    +    endTimeUnixNano: unixNanoseconds(endedAt),
    +    attributes: input.attributes,
    +    status: { code: input.status === 'success' ? 1 : input.status === 'error' ? 2 : 0 },
    +  };
    +}
    +
    +function stringAttribute(key: string, value: string): OtlpAttribute {
    +  return { key, value: { stringValue: value } };
    +}
    +
    +function numberAttribute(key: string, value: number): OtlpAttribute {
    +  return { key, value: { doubleValue: value } };
    +}
    +
    +function resolveEndpoint(env: Environment): string | undefined {
    +  const configured = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
    +  if (!configured) return undefined;
    +  try {
    +    const url = new URL(configured);
    +    const pathname = url.pathname.replace(/\/+$/u, '');
    +    url.pathname = pathname.endsWith('/v1/traces') ? pathname : `${pathname}/v1/traces`;
    +    return url.toString();
    +  } catch {
    +    return undefined;
    +  }
    +}
    +
    +function parseHeaders(value: string | undefined): Record<string, string> {
    +  if (!value) return {};
    +  const headers = Object.create(null) as Record<string, string>;
    +  const names = new Set<string>();
    +  let encodedBytes = 0;
    +  for (const item of value.split(',')) {
    +    const separator = item.indexOf('=');
    +    if (separator <= 0) continue;
    +    const key = item.slice(0, separator).trim();
    +    const raw = item.slice(separator + 1).trim();
    +    if (
    +      !key ||
    +      key.length > MAX_HEADER_NAME_LENGTH ||
    +      !HEADER_NAME.test(key) ||
    +      PROTECTED_HEADERS.has(key.toLowerCase())
    +    ) {
    +      continue;
    +    }
    +    const lowerKey = key.toLowerCase();
    +    if (names.has(lowerKey) || names.size >= MAX_HEADER_COUNT) continue;
    +    const decoded = decodeValue(raw);
    +    if (
    +      !raw ||
    +      decoded.length > MAX_HEADER_VALUE_LENGTH ||
    +      /[^\t\u0020-\u007e\u0080-\u00ff]/u.test(decoded)
    +    ) {
    +      continue;
    +    }
    +    const entryBytes = new TextEncoder().encode(`${key}:${decoded}`).byteLength;
    +    if (encodedBytes + entryBytes > MAX_HEADER_BYTES) break;
    +    encodedBytes += entryBytes;
    +    names.add(lowerKey);
    +    headers[key] = decoded;
    +  }
    +  return headers;
    +}
    +
    +function warnForInsecureAuthorization(endpoint: string, headers: Record<string, string>): void {
    +  let url: URL;
    +  try {
    +    url = new URL(endpoint);
    +  } catch {
    +    return;
    +  }
    +  if (url.protocol === 'https:') return;
    +  const hasAuthorization = Object.keys(headers).some(
    +    (name) => name.toLowerCase() === 'authorization',
    +  );
    +  if (hasAuthorization && !insecureAuthorizationWarnings.has(endpoint)) {
    +    insecureAuthorizationWarnings.add(endpoint);
    +    console.warn(
    +      '[telemetry] OTLP endpoint is not using HTTPS while an authorization header is configured; credentials and telemetry will be sent without transport encryption',
    +    );
    +  }
    +}
    +
    +function boundedErrorClass(value: string | undefined): string | undefined {
    +  if (!value) return undefined;
    +  const sanitized = value.trim().replace(/[\u0000-\u001f\u007f-\u009f]/gu, '');

    Addressed in f9d793381. The outbound boundary now projects errorClass onto a fixed set of known runtime classes and maps all other names to Other. Both model and tool exports use this projection. Regression coverage includes sk-live-secret-value and an arbitrary password-shaped name, while known Timeout/InvalidArguments remain useful. The former truncation-only implementation fails these cases.

    Automated follow-up by OpenAI Codex for @seekskyworld.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 15:39 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,348 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const MAX_ERROR_CLASS_LENGTH = 128;
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  async close(): Promise<void> {
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    await this.flush();
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    try {
    +      const response = await this.#fetch(this.#endpoint, {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json', ...this.#headers },
    +        body: JSON.stringify({
    +          resourceSpans: [
    +            {
    +              resource: { attributes: this.#resourceAttributes },
    +              scopeSpans: [{ scope: { name: 'maka.storage' }, spans }],
    +            },
    +          ],
    +        }),
    +      });
    +      if (!response.ok) {
    +        console.error(`[telemetry] OTLP export failed: HTTP ${response.status}`);

    Addressed in f9d793381. Collector failures are reported once until a successful export resets the warning state. A 503,503,200,503,503 sequence produces two logs; the previous implementation produces four. Requests remain best-effort without replaying failed batches.

    Automated follow-up by OpenAI Codex for @seekskyworld.

    hqhq1025 hqhq1025 commented on code on Sep 15, 2026 16:15 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,423 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS,

    [P2] Treat empty signal-specific environment values as unset before applying precedence. The OpenTelemetry environment-variable specification requires an empty value to behave exactly like an unset variable, but ?? selects '' here. On this head, OTEL_EXPORTER_OTLP_TRACES_HEADERS='' removes a valid generic authorization header; the same pattern at resolveEndpoint disables the exporter when the generic endpoint is valid, and at resolveTimeout ignores a valid generic timeout. I reproduced the endpoint case as exporter === undefined and the header case as a request containing only content-type. Please fall back to the generic value for empty signal-specific strings and update the README/test that currently defines empty headers as an override. Spec: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#parsing-empty-value

    hqhq1025 hqhq1025 commented on code on Sep 15, 2026 16:15 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,423 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS,
    +  );
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +    resolveTimeout(env),
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  readonly #timeoutMs: number;
    +  readonly #shutdown = new AbortController();
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +  #closePromise: Promise<void> | undefined;
    +  #failureReported = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +    timeoutMs: number,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +    this.#timeoutMs = timeoutMs;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  close(): Promise<void> {
    +    if (this.#closePromise) return this.#closePromise;
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    const timer = setTimeout(() => this.#shutdown.abort(), CLOSE_TIMEOUT_MS);
    +    this.#closePromise = this.flush().finally(() => clearTimeout(timer));
    +    return this.#closePromise;
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    if (this.#shutdown.signal.aborted) return;
    +    const controller = new AbortController();
    +    const abort = () => controller.abort();
    +    const timer = setTimeout(abort, this.#timeoutMs);
    +    this.#shutdown.signal.addEventListener('abort', abort, { once: true });
    +    const cancelled = new Promise<never>((_resolve, reject) => {
    +      controller.signal.addEventListener(
    +        'abort',
    +        () => reject(new Error('OTLP request cancelled')),
    +        { once: true },
    +      );
    +    });
    +    try {
    +      // 同时约束请求及响应释放;即使注入的 transport 不响应 AbortSignal,也不阻塞关闭。
    +      const response = await Promise.race([this.sendRequest(spans, controller.signal), cancelled]);
    +      if (response.ok) {
    +        this.#failureReported = false;
    +      } else {
    +        this.reportFailure(`HTTP ${response.status}`);

    [P2] Retry transient OTLP failures instead of dropping this batch after the first attempt. flush() removes the spans from #pending, and this branch only logs, so retryable 429/502/503/504 responses and connection failures are permanently lost. A probe where the first response was 503 Retry-After: 0 and the next would be 200 made exactly one request even after another flush() and close(). The stable OTLP exporter specification requires transient errors to use exponential backoff with jitter; best-effort delivery can remain non-fatal while still retrying within the configured batch timeout and honoring shutdown cancellation. Spec: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#retry

    hqhq1025 hqhq1025 commented on Sep 15, 2026 16:15 UTC
    Reviewer

    Reviewed current head f9d7933815fc4a55234829630a1c75881c27270f. This follow-up fixes the previously reported shutdown hang, trace endpoint/header handling, outbound error-class leakage, and repeated failure logging. Two P2 protocol/configuration findings remain below, so this is not technically ready. Because this adds a new opt-in outbound telemetry path, the final product and merge decision also remains with a human maintainer.

    Validation on this exact head: clean install with Node 24.18.1; build:test; full workspace typecheck; Storage 1,130 passed / 10 skipped; focused exporter and Usage tests 30/30; lint; format; ASF headers; git diff --check; hosted test green; and a clean merge tree against current main 3dcf5a125447ad210649f2e3414512aa79813c0a.

    Direct probes confirmed both findings: empty trace-specific endpoint/header values override working generic values, and a retryable HTTP 503 with Retry-After: 0 followed by an available success response still resulted in exactly one request and permanent loss of the batch. No live third-party collector or non-Linux shutdown path was exercised.

    Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 16:53 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,423 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS,

    Addressed in 8dba766f4. Empty trace-specific endpoint, headers and timeout values now fall back to their generic counterparts; the generic endpoint still receives /v1/traces. Updated the README and regressions. The previous implementation fails all three empty-value cases. OpenAI Codex assisted with this follow-up.

    seekskyworld seekskyworld commented on code on Sep 15, 2026 16:53 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,423 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS,
    +  );
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +    resolveTimeout(env),
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  readonly #timeoutMs: number;
    +  readonly #shutdown = new AbortController();
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +  #closePromise: Promise<void> | undefined;
    +  #failureReported = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +    timeoutMs: number,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +    this.#timeoutMs = timeoutMs;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  close(): Promise<void> {
    +    if (this.#closePromise) return this.#closePromise;
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    const timer = setTimeout(() => this.#shutdown.abort(), CLOSE_TIMEOUT_MS);
    +    this.#closePromise = this.flush().finally(() => clearTimeout(timer));
    +    return this.#closePromise;
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));
    +    if (this.#pending.length >= BATCH_SIZE) {
    +      await this.flush();
    +      return;
    +    }
    +    if (!this.#timer) {
    +      this.#timer = setTimeout(() => {
    +        this.#timer = undefined;
    +        void this.flush();
    +      }, FLUSH_DELAY_MS);
    +    }
    +  }
    +
    +  private async send(spans: OtlpSpan[]): Promise<void> {
    +    if (this.#shutdown.signal.aborted) return;
    +    const controller = new AbortController();
    +    const abort = () => controller.abort();
    +    const timer = setTimeout(abort, this.#timeoutMs);
    +    this.#shutdown.signal.addEventListener('abort', abort, { once: true });
    +    const cancelled = new Promise<never>((_resolve, reject) => {
    +      controller.signal.addEventListener(
    +        'abort',
    +        () => reject(new Error('OTLP request cancelled')),
    +        { once: true },
    +      );
    +    });
    +    try {
    +      // 同时约束请求及响应释放;即使注入的 transport 不响应 AbortSignal,也不阻塞关闭。
    +      const response = await Promise.race([this.sendRequest(spans, controller.signal), cancelled]);
    +      if (response.ok) {
    +        this.#failureReported = false;
    +      } else {
    +        this.reportFailure(`HTTP ${response.status}`);

    Addressed in 8dba766f4. Connection failures and HTTP 429/502/503/504 retry the identical batch with exponential backoff and jitter, honoring Retry-After seconds/dates. All attempts and backoff waits share the original batch timeout and shutdown cancellation. Permanent HTTP failures remain non-retryable. Tests cover retry payload identity, response-body cancellation, exponential waits, and cancellation during Retry-After. All 14 exporter tests and the Storage suite (1135 pass, 8 platform skips), full repository build/typecheck/lint/format and Desktop/UI knip pass. OpenAI Codex assisted with this follow-up.

    hqhq1025 hqhq1025 commented on Sep 15, 2026 18:28 UTC
    Reviewer

    Reviewed current head 8dba766f442fa7010450029613f793eca0134e09. The latest follow-up fixes both P2 findings from the previous head: empty trace-specific endpoint/header/timeout variables now fall back to their generic OTLP settings, and transient connection failures plus HTTP 429/502/503/504 responses retry within the original batch deadline without changing the serialized batch. I found no remaining P0-P3 issue on this head.

    The five-file change adds an opt-in OTLP/HTTP exporter to the durable usage writer. The final implementation keeps the exporter disabled without an endpoint, validates outbound headers, allowlists error classes, uses exact trace-specific endpoint semantics, bounds request and shutdown time, and retries only the documented transient failures (packages/storage/src/otlp-telemetry-exporter.ts:100-115, 202-209, 233-315, 347-367, 370-429; packages/storage/src/usage-stores.ts:424-486). The new tests cover the real file-backed writer shutdown path as well as endpoint/header/timeout precedence and retry identity.

    Validation on this exact head: clean Node 24.18.1 install; build:test; full workspace typecheck; Storage 1,133 passed / 10 skipped; full lint and format checks; ASF headers; changed-file Biome; git diff --check; hosted test green; and a clean merge tree against current main 2c49a9986fc4cbc6f09c1afb2c9d205b67c86a7b (tree 0afa1135885480cde466c35c672092f0915f708d). An independent local-collector probe confirmed that empty trace-specific values use the generic endpoint/header/timeout, a 503 with Retry-After: 0 retries once with an identical payload and succeeds, a connection failure recovers on retry, and shutdown cancels a long retry wait in about 1.0 seconds.

    I did not exercise a live third-party collector or native Windows/macOS shutdown. This remains a new opt-in outbound telemetry feature, so the product and merge decision still requires a human maintainer.

    Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

    me2seeks me2seeks commented on Sep 28, 2026 16:01 UTC
    Reviewer

    Automated review notice: This comment was posted by an automated review agent operated by me2seeks make. It is not an independent human review and does not replace one.

    Summary


    Adds opt-in OTLP usage traces: a new otlp-telemetry-exporter.ts (bounded batching with timers/promises delays, PersistedLlmCallRecord shaping) integrated into usage-stores.ts, documented in the CLI README, and covered by a 560-line exporter test plus usage-stores assertions. Being opt-in is the correct privacy default — usage traces carry model-call metadata and must not flow to a collector without explicit configuration. test lane passes.

    Findings


    1. [P3] Confirm the exporter's records never include prompt/response bodies (usage/cost metadata only) — the record type is PersistedLlmCallRecord, and the exporter test should pin that no content fields are emitted; telemetry exfiltrating prompt text would be a privacy regression. Verification, not a proven defect.

    Verdict


    merge-ready — opt-in telemetry with a tested exporter; request the no-content assertion as a follow-up if not already covered.

    seekskyworld seekskyworld commented on Oct 10, 2026 08:24 UTC
    Author

    Confirmed by inspecting exportLlmCall and enqueue: spans are constructed from an explicit usage/identity/status attribute allowlist; the exporter does not serialize the input record or accept prompt/response bodies. The existing payload assertions exclude argsSummary, and arbitrary error classes are normalized to an allowlist (the secret-value regression also checks the serialized request). This is a verification of the current implementation, not a claim that user-configured OTEL_RESOURCE_ATTRIBUTES cannot contain user-supplied text.

    Automated update by OpenAI Codex under the contributor’s direction.

    Astro-Han Astro-Han commented on code on Oct 10, 2026 12:59 UTC
    Code Review
    packages/storage/src/usage-stores.ts:1
    @@ -500,9 +508,15 @@ function createWriterFacade(
           latestLlmRuntimeProbe: (connectionSlug, modelId) =>
             read(() => telemetry.latestLlmRuntimeProbe(connectionSlug, modelId)),
           recordLlmCall: (record) =>
    -        admitSessionUsageMutation(record.sessionId, () => telemetry.insertLlmCall(record)),
    +        admitSessionUsageMutation(record.sessionId, async () => {
    +          await telemetry.insertLlmCall(record);
    +          void exporter?.exportLlmCall(record);

    [P2] This exports only legacy LLM records, not normal conversation calls. The production Backend now records physical ModelCallAttempt commits through execution-model-composition.ts:266–280, then modelCalls.catchUpModelCallProjection; the old send-level recordLlmCall was deliberately removed. Through a real file-backed writer, one canonical attempt appeared in the local Usage summary but produced zero HTTP requests after flush, while tool records reached the same collector. Auxiliary calls still use this legacy hook and can mask the omission. Export canonical attempt settlements without reinstating a second send-level meter, and cover that actual accounting path.

    Astro-Han Astro-Han commented on code on Oct 10, 2026 12:59 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,458 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import { setTimeout as delay } from 'node:timers/promises';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +const INITIAL_RETRY_DELAY_MS = 1_000;
    +const MAX_RETRY_DELAY_MS = 30_000;
    +const RETRYABLE_HTTP_STATUSES = new Set([429, 502, 503, 504]);
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS || env.OTEL_EXPORTER_OTLP_HEADERS,
    +  );
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +    resolveTimeout(env),
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  readonly #timeoutMs: number;
    +  readonly #shutdown = new AbortController();
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +  #closePromise: Promise<void> | undefined;
    +  #failureReported = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +    timeoutMs: number,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +    this.#timeoutMs = timeoutMs;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;

    [P2] Share a promise for the entire drain, not only the current send. After concurrent callers await batch A, one starts batch B and empties the queue; close's caller can then return and disarm the one-second shutdown timer even though B is active. With 64 persisted tool records and a real local collector, close returned in about 18 ms, but the isolated writer process remained alive another 10,005 ms under the default request timeout. A generated-code comparison sharing the whole drain cancelled B after one second and exited about 11 ms later; restoring this code reproduced the delay. Add a two-batch shutdown regression that verifies cancellation and natural process exit.

    Astro-Han Astro-Han commented on code on Oct 10, 2026 12:59 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,458 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import { setTimeout as delay } from 'node:timers/promises';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +const INITIAL_RETRY_DELAY_MS = 1_000;
    +const MAX_RETRY_DELAY_MS = 30_000;
    +const RETRYABLE_HTTP_STATUSES = new Set([429, 502, 503, 504]);
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS || env.OTEL_EXPORTER_OTLP_HEADERS,
    +  );
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +    resolveTimeout(env),
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  readonly #timeoutMs: number;
    +  readonly #shutdown = new AbortController();
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +  #closePromise: Promise<void> | undefined;
    +  #failureReported = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +    timeoutMs: number,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +    this.#timeoutMs = timeoutMs;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  close(): Promise<void> {
    +    if (this.#closePromise) return this.#closePromise;
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    const timer = setTimeout(() => this.#shutdown.abort(), CLOSE_TIMEOUT_MS);
    +    this.#closePromise = this.flush().finally(() => clearTimeout(timer));
    +    return this.#closePromise;
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));

    [P3] BATCH_SIZE is only a trigger, not a queue or batch ceiling. Storage callers deliberately do not await export, so a stalled request permits continued appends; splice(0) subsequently takes the entire backlog. A controlled 4,096-record backlog produced one 4,096-span request. Define explicit queue/batch limits and an overflow policy while keeping the local ledger authoritative. I did not reproduce memory exhaustion or collector rejection, so those are potential consequences, not demonstrated failures.

    Astro-Han Astro-Han commented on Oct 10, 2026 12:59 UTC
    Reviewer

    Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

    I found two P2 issues and one P3 in e7b7d53d4e9cbff2844454ab68a5a9b33ea226a1:

  • P2 — Normal conversational model calls are not exported (packages/storage/src/usage-stores.ts:513). Only the legacy telemetry.recordLlmCall path invokes the exporter. Current main conversations persist ModelCallAttempt records and call modelCalls.catchUpModelCallProjection; that path never invokes it. A real file-backed writer projected one canonical model call into the local Usage summary, but flushing produced zero HTTP exports. Tool exports used the same configured collector successfully. Auxiliary calls still use the legacy path, so their spans do not demonstrate coverage of normal conversations. Connect the export to canonical physical-attempt settlement without restoring the removed duplicate send-level meter.

  • P2 — Concurrent batches bypass the shutdown deadline (packages/storage/src/otlp-telemetry-exporter.ts:188–198). Multiple flush() callers await the current batch, but only one drains the next batch. close() can return after the first batch finishes, see an empty queue, and cancel the one-second shutdown timer while the next request is still active. With 64 persisted tool records and a real local collector, close returned in about 18 ms, then an isolated Node process remained alive for 10,005 ms under the unmodified default request timeout. Sharing one promise for the entire drain, rather than an individual send, made close cancel the second request after about one second and allowed the process to exit about 11 ms later. This was a disposable generated-code comparison, not a submitted fix; the original code was restored and the failure reproduced. I did not launch a complete Host lifecycle, but its normal exit path also relies on the Node event loop ending.

  • P3 — Batching has no queue or batch-size ceiling (packages/storage/src/otlp-telemetry-exporter.ts:190,220). The value 32 is only a flush trigger. While one request is stalled, fire-and-forget producers keep appending, and the next splice(0) sends everything. A controlled 4,096-record backlog became one 4,096-span request. Set explicit queue and batch limits with a documented best-effort overflow policy. I did not reproduce collector rejection or memory exhaustion, so I am not treating those potential consequences as demonstrated P2 failures.
  • The earlier single-request shutdown hang, endpoint/header/timeout precedence, empty environment overrides, error-class leakage, timestamp precision and repeated-error logging issues are resolved. The OTLP endpoint and retry rules and empty-value rules match the corrected branches. Additional probes confirmed default-off behavior, omitted content/credential/path sentinels for both record types, fixed error-class projection, protected-header handling and exact nanosecond strings. The previous request to verify omitted content fields is satisfied, not a separate privacy defect.

    Validation: fresh dependencies and Core/Storage builds passed; all 39 complete exporter/Usage tests passed before and after restoring the comparison. The full Storage run had 1,408 passed, 11 skipped, one failed: an unrelated subprocess test rejected Node 22's experimental SQLite warning on stderr; that complete five-test file passed with warnings suppressed. Changed-file Biome and whitespace checks passed. The head remains unchanged, its hosted test is successful, and GitHub reports MERGEABLE. A local merge with main 685d3ab243fd9a91c774956db6018129040ae667 is conflict-free and retains both P2 paths; no merged-build claim is made. No Host wire change or epoch bump is needed.

    No live third-party collector or native Windows/macOS shutdown was exercised. This is a new outbound telemetry feature, so its adoption and merge decision remains with a human maintainer, independently of fixing the two correctness issues.

    seekskyworld seekskyworld commented on code on Oct 12, 2026 08:53 UTC
    Code Review
    packages/storage/src/usage-stores.ts:1
    @@ -500,9 +508,15 @@ function createWriterFacade(
           latestLlmRuntimeProbe: (connectionSlug, modelId) =>
             read(() => telemetry.latestLlmRuntimeProbe(connectionSlug, modelId)),
           recordLlmCall: (record) =>
    -        admitSessionUsageMutation(record.sessionId, () => telemetry.insertLlmCall(record)),
    +        admitSessionUsageMutation(record.sessionId, async () => {
    +          await telemetry.insertLlmCall(record);
    +          void exporter?.exportLlmCall(record);

    Fixed in 63a3d2b1f. The Usage facade observes newly inserted canonical attempts only after the projection transaction commits. The callback does not await network I/O or create a second send-level record. Real file-backed authority events now reach a local collector; repeated catch-up/reopen and duplicate attempt events do not re-export rows. Missing usage/unpriced cost stays absent, and rollback does not export. The old merged implementation fails with zero spans; current Node 22 focused tests (75) and full Storage (1,654 pass / 8 skip) pass.

    Automated update by OpenAI Codex under the contributor’s direction.

    seekskyworld seekskyworld commented on code on Oct 12, 2026 08:53 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,458 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import { setTimeout as delay } from 'node:timers/promises';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +const INITIAL_RETRY_DELAY_MS = 1_000;
    +const MAX_RETRY_DELAY_MS = 30_000;
    +const RETRYABLE_HTTP_STATUSES = new Set([429, 502, 503, 504]);
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS || env.OTEL_EXPORTER_OTLP_HEADERS,
    +  );
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +    resolveTimeout(env),
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  readonly #timeoutMs: number;
    +  readonly #shutdown = new AbortController();
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +  #closePromise: Promise<void> | undefined;
    +  #failureReported = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +    timeoutMs: number,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +    this.#timeoutMs = timeoutMs;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;

    Fixed in 63a3d2b1f: concurrent flush callers share the promise for the entire drain, including later batches. Added an isolated real writer process with 64 persisted tool records and an HTTP collector that releases batch one during close and stalls batch two. The test asserts cancellation and natural process exit within five seconds under the default ten-second request timeout. It fails on the old implementation; the fixed writer exits after the one-second grace on Node 24 and Node 22.

    Automated update by OpenAI Codex under the contributor’s direction.

    seekskyworld seekskyworld commented on code on Oct 12, 2026 08:53 UTC
    Code Review
    packages/storage/src/otlp-telemetry-exporter.ts:1
    @@ -0,0 +1,458 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { randomUUID } from 'node:crypto';
    +import { setTimeout as delay } from 'node:timers/promises';
    +import type {
    +  PersistedLlmCallRecord,
    +  PersistedToolInvocationRecord,
    +} from './telemetry-file-schema.js';
    +
    +const BATCH_SIZE = 32;
    +const FLUSH_DELAY_MS = 1_000;
    +const DEFAULT_SERVICE_NAME = 'maka';
    +const MAX_HEADER_COUNT = 32;
    +const MAX_HEADER_NAME_LENGTH = 128;
    +const MAX_HEADER_VALUE_LENGTH = 8_192;
    +const MAX_HEADER_BYTES = 64 * 1_024;
    +const DEFAULT_TIMEOUT_MS = 10_000;
    +const INITIAL_RETRY_DELAY_MS = 1_000;
    +const MAX_RETRY_DELAY_MS = 30_000;
    +const RETRYABLE_HTTP_STATUSES = new Set([429, 502, 503, 504]);
    +// Host 在 10 秒后强制终止;导出器关闭最多占用 1 秒,为其余资源清理保留时间。
    +const CLOSE_TIMEOUT_MS = 1_000;
    +const ERROR_CLASSES = new Set([
    +  'Abort',
    +  'Auth',
    +  'ContextLength',
    +  'Network',
    +  'Timeout',
    +  'RateLimit',
    +  'ProviderBilling',
    +  'ProviderCapacity',
    +  'ProviderUnavailable',
    +  'Other',
    +  'ExclusiveStepConflict',
    +  'InvalidArguments',
    +  'AmbiguousComputerTarget',
    +  'LoopGate',
    +  'DeferredNotLoaded',
    +  'ExecutionBoundaryUnavailable',
    +  'ClientCapabilityBoundary',
    +  'ClientCapabilityPreparation',
    +  'RuntimeLimit',
    +  'OutcomeUnknown',
    +]);
    +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
    +const PROTECTED_HEADERS = new Set([
    +  'connection',
    +  'content-length',
    +  'content-type',
    +  'host',
    +  'proxy-connection',
    +  'transfer-encoding',
    +]);
    +const insecureAuthorizationWarnings = new Set<string>();
    +
    +type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
    +type Environment = Record<string, string | undefined>;
    +type OtlpAttributeValue = { stringValue: string } | { intValue: string } | { doubleValue: number };
    +type OtlpAttribute = { key: string; value: OtlpAttributeValue };
    +type OtlpSpan = {
    +  traceId: string;
    +  spanId: string;
    +  name: string;
    +  kind: 1;
    +  startTimeUnixNano: string;
    +  endTimeUnixNano: string;
    +  attributes: OtlpAttribute[];
    +  status: { code: 0 | 1 | 2 };
    +};
    +
    +export interface OtlpTelemetryExporter {
    +  exportLlmCall(record: PersistedLlmCallRecord): Promise<void>;
    +  exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void>;
    +  flush(): Promise<void>;
    +  close(): Promise<void>;
    +}
    +
    +export interface OtlpTelemetryExporterOptions {
    +  readonly env?: Environment;
    +  readonly fetch?: FetchLike;
    +}
    +
    +export function createOtlpTelemetryExporter(
    +  options: OtlpTelemetryExporterOptions = {},
    +): OtlpTelemetryExporter | undefined {
    +  const env = options.env ?? process.env;
    +  const endpoint = resolveEndpoint(env);
    +  if (!endpoint) return undefined;
    +  const headers = parseHeaders(
    +    env.OTEL_EXPORTER_OTLP_TRACES_HEADERS || env.OTEL_EXPORTER_OTLP_HEADERS,
    +  );
    +  warnForInsecureAuthorization(endpoint, headers);
    +  return new OtlpTelemetryExporterImpl(
    +    endpoint,
    +    headers,
    +    resourceAttributes(env),
    +    options.fetch ?? fetch,
    +    resolveTimeout(env),
    +  );
    +}
    +
    +class OtlpTelemetryExporterImpl implements OtlpTelemetryExporter {
    +  readonly #endpoint: string;
    +  readonly #headers: Record<string, string>;
    +  readonly #resourceAttributes: OtlpAttribute[];
    +  readonly #fetch: FetchLike;
    +  readonly #pending: OtlpSpan[] = [];
    +  readonly #timeoutMs: number;
    +  readonly #shutdown = new AbortController();
    +  #timer: NodeJS.Timeout | undefined;
    +  #flushPromise: Promise<void> | undefined;
    +  #closed = false;
    +  #closePromise: Promise<void> | undefined;
    +  #failureReported = false;
    +
    +  constructor(
    +    endpoint: string,
    +    headers: Record<string, string>,
    +    resourceAttributes: OtlpAttribute[],
    +    fetchFn: FetchLike,
    +    timeoutMs: number,
    +  ) {
    +    this.#endpoint = endpoint;
    +    this.#headers = headers;
    +    this.#resourceAttributes = resourceAttributes;
    +    this.#fetch = fetchFn;
    +    this.#timeoutMs = timeoutMs;
    +  }
    +
    +  async exportLlmCall(record: PersistedLlmCallRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.llm.call',
    +      startedAt: record.startedAt,
    +      durationMs: record.latencyMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'llm'),
    +        stringAttribute('maka.provider.id', record.providerId),
    +        stringAttribute('maka.model.id', record.modelId),
    +        ...(record.callKind ? [stringAttribute('maka.call.kind', record.callKind)] : []),
    +        numberAttribute('maka.usage.input_tokens', record.inputTokens),
    +        numberAttribute('maka.usage.output_tokens', record.outputTokens),
    +        numberAttribute('maka.usage.total_tokens', record.totalTokens),
    +        numberAttribute('maka.usage.cost_usd', record.costUsd),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async exportToolInvocation(record: PersistedToolInvocationRecord): Promise<void> {
    +    const errorClass = boundedErrorClass(record.errorClass);
    +    await this.enqueue({
    +      name: 'maka.tool.invocation',
    +      startedAt: record.startedAt,
    +      durationMs: record.durationMs,
    +      status: record.status,
    +      attributes: [
    +        stringAttribute('maka.telemetry.kind', 'tool'),
    +        stringAttribute('maka.tool.name', record.toolName),
    +        ...(record.providerId ? [stringAttribute('maka.provider.id', record.providerId)] : []),
    +        ...(record.modelId ? [stringAttribute('maka.model.id', record.modelId)] : []),
    +        numberAttribute('maka.tool.bytes_in', record.bytesIn),
    +        numberAttribute('maka.tool.bytes_out', record.bytesOut),
    +        ...(errorClass ? [stringAttribute('maka.error.class', errorClass)] : []),
    +      ],
    +    });
    +  }
    +
    +  async flush(): Promise<void> {
    +    if (this.#flushPromise) await this.#flushPromise;
    +    while (this.#pending.length > 0) {
    +      const spans = this.#pending.splice(0);
    +      if (this.#timer) {
    +        clearTimeout(this.#timer);
    +        this.#timer = undefined;
    +      }
    +      this.#flushPromise = this.send(spans).finally(() => {
    +        this.#flushPromise = undefined;
    +      });
    +      await this.#flushPromise;
    +    }
    +  }
    +
    +  close(): Promise<void> {
    +    if (this.#closePromise) return this.#closePromise;
    +    this.#closed = true;
    +    if (this.#timer) clearTimeout(this.#timer);
    +    this.#timer = undefined;
    +    const timer = setTimeout(() => this.#shutdown.abort(), CLOSE_TIMEOUT_MS);
    +    this.#closePromise = this.flush().finally(() => clearTimeout(timer));
    +    return this.#closePromise;
    +  }
    +
    +  private async enqueue(input: {
    +    name: string;
    +    startedAt: number;
    +    durationMs: number;
    +    status: PersistedLlmCallRecord['status'];
    +    attributes: OtlpAttribute[];
    +  }): Promise<void> {
    +    if (this.#closed) return;
    +    this.#pending.push(toSpan(input));

    Fixed in 63a3d2b1f: requests are capped at 32 spans, pending spans at 1,024 plus one in-flight batch, and overflow drops newest optional exports. The local ledger remains authoritative. A stalled 4,096-record producer regression verifies the cap and retained order; the old implementation fails. Limits and loss semantics are documented in the CLI README and PR description.

    Automated update by OpenAI Codex under the contributor’s direction.

    Astro-Han Astro-Han commented on Oct 12, 2026 09:28 UTC
    Reviewer

    Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

    I reviewed 63a3d2b1ff95c2f21a2f41abda6ffe4fa2cb6bab, incrementally from e7b7d53d and against current main 6ffa2030d.

    Both previous P2 findings are fixed. Canonical physical model attempts now reach the exporter only after the Usage projection transaction commits (model-call-ledger.ts:275–290, usage-stores.ts:460–470). My actual file-backed writer/local HTTP collector probe exports the committed attempt once; repeated catch-up and reopening do not duplicate it. The complete ledger/Usage tests also cover rollback-before-export, missing usage, unpriced cost and omission of request evidence. This adds no second conversation meter or historical backfill.

    Concurrent flush callers now join the complete drain, including later batches (otlp-telemetry-exporter.ts:235–270). In the independent real HTTP/two-batch writer probe, close takes approximately one second and cancels the stalled second request. A separate writer process, with default timeout configuration, then exits naturally approximately 13 ms after close returns rather than lingering for the previous ten-second request timeout. Neither probe forces a successful process exit. The old queue P3 is also fixed: requests have a hard 32-span bound and pending exports a 1,024-span bound. The 4,096-record regression verifies 32 + 1,024 accepted exports with newer overflow dropped; the local ledger remains authoritative.

    Current CI is red for an inherited WorkHub close race, not a confirmed defect introduced by this PR. The exact-head failure is a call clearing receipt cannot erase the current remote heading, whose cleanup observes WorkHub remote transport is inactive. The bridge, test and dependent fixture/helper sources match main byte-for-byte. Loading both Git versions and closing while the Turn query is deliberately suspended reproduces the same inactive-transport error in both; the ordinary complete bridge file passes locally (23 tests). This is unrelated to OTLP and is not the former packaged missing-renderer-helper failure. It still means this exact head is not fully green.

    Fresh dependencies/patches and the normal clean workspace test build passed on Linux/Node 22.23.2. The three complete exporter/Usage/ledger test files passed 75 tests, without failures, cancellations or skips. Storage typecheck, changed-file Biome, diff and protocol checks passed. Independent probes also confirm default-off behavior, content/credential omission, header precedence and exact nanoseconds. The merge with main 6ffa2030d is clean, with no authored protocol or database-schema change (epoch 217).

    I found no new confirmed P0–P2 defect in this increment. These tests do not qualify a live third-party collector, durable exactly-once network delivery, or the full Host/Desktop shutdown path. I did not rerun the complete Storage/repository suites or native Desktop acceptance. Feature adoption and the handwritten-exporter tradeoff remain separate from this correctness verification.

    M4n5ter M4n5ter commented on Nov 29, 2026 05:22 UTC
    Contributor

    Closing this PR because main switched from the legacy TypeScript codebase to the Rust architecture in #7157, and pre-switch PRs are no longer being merged. Thanks for the contribution—if this change is still relevant, please feel free to open a new PR based on the current main.

    Reviewers
    Assignees
    seekskyworld seekskyworld
    Labels
    risk: low confidence: 81.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 58.2% (MEDIUM) · Higher = larger blast radius
    58.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 81.1% · Lower = rushed or shallow review
    81.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 11.0% · Safe to merge
    11.0%
    Repository