Skip to content

feat(telemetry): OpenTelemetry recorder, infer stats, and OTLP export - #892

Merged
edenreich merged 7 commits into
mainfrom
feat/metrics-recorder-stats
Jul 12, 2026
Merged

edenreich merged 7 commits into
mainfrom
feat/metrics-recorder-stats

Conversation

@edenreich

@edenreich edenreich commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #841. Closes #842.

CLI telemetry recorded once into OpenTelemetry instruments and written by OTel exporters — locally by default, and to your own collector when you opt in. One semconv format everywhere; no custom on-disk shape.

How

One instrumentation path. Tool outcomes, token usage, and sessions are recorded into OpenTelemetry SDK instruments named per the GenAI semantic conventions + infer-action's exporter. The recorded data is written by OTel exporters, unchanged:

  • local (always, private): the SDK's stdout exporter appended to a per-session file under ~/.infer/telemetry/ — OTLP/semconv JSON as-is, no custom naming. Powers infer stats.
  • remote (opt-in): the OTLP/HTTP exporter, active only when telemetry.otlp.endpoint (or OTEL_EXPORTER_OTLP_ENDPOINT) is set. When unset, no exporter connects and nothing leaves the machine.

Both use delta temporality — what the gateway's OTLP ingest requires, and what makes the local files trivially summable by infer stats.

Taps: the tool decorator wraps the container tool service (covers chat + the headless subprocess); one usage tap in storeIterationMetrics (the shared #835 accumulator); one session record per run in the chat/headless commands.

infer stats [--since 7d] [--format json] parses the local OTLP files and renders: tool calls (count, fail%, avg), tokens + cost by model, and sessions by execution × agent mode.

Instruments (match the gateway ingest + infer-action)

event instrument key attributes
usage gen_ai.client.token.usage (histogram) gen_ai.request.model, gen_ai.provider.name, gen_ai.token.type
usage infer.client.cost (sum, USD) gen_ai.request.model, infer.cost.type
tool infer.agent.tool.calls (counter) gen_ai.tool.name, infer.tool.outcome, error.type
tool gen_ai.execute_tool.duration (histogram, s) gen_ai.tool.name, gen_ai.tool.type, error.type
session infer.agent.runs (counter) + infer.agent.run.duration (s) infer.run.outcome, infer.agent.mode

Every metric also carries, via the resource: service.name=infer, service.version (which CLI version), and infer.execution.mode = interactive (chat) vs headless (infer agent).

Config

telemetry:
  enabled: true            # record locally
  retention_days: 90
  otlp:
    endpoint: ""           # set (or OTEL_EXPORTER_OTLP_ENDPOINT) to ALSO export; empty = local only
    headers: {}
    interval: 60

Tests / verification

  • internal/telemetry: full round-trip (record → stdout-exporter file → parse via Aggregate) asserting 1 failure + 142 tokens + execution mode; empty store; disabled=nil; provider-from-model; and a semconv-value pin (success/error/failed/stopped_early/tool_error/interactive/headless) so a rename that breaks the shared contract fails the build.
  • tests/integration/telemetry_test.go (acceptance): failing tool → 1 failure; usage-report → 142 tokens. The shared newEnv sandboxes HOME so no test touches the real ~/.infer.
  • Manual: verified the local file is OTLP/semconv JSON carrying service.version + infer.execution.mode, infer stats renders it, and the OTLP/HTTP exporter pushes to a live local collector (/v1/metrics) while the local file is written too.
  • task test, task lint, task test:e2e all green.

Acceptance criteria

#841: [x] failing tool + usage-report → 1 failure / 142 tokens · [x] clean empty-store render · [x] no decorator on the tool path when disabled
#842: [x] visible via a local otel collector · [x] no exporter initialized when the endpoint is unset · [x] exporter failures logged and dropped

Notes / follow-ups

  • Metric names follow the GenAI semconv the gateway/infer-action already use (refining [FEATURE] OTLP metrics exporter #842's draft infer.tool.* names) — chosen for max OTel compatibility and gateway-ingestibility; pinned by a test.
  • [FEATURE] Opt-in anonymous usage telemetry for maintainers #843 (opt-in anonymous telemetry to a maintainer collector, with a consent prompt) stays separate — this only lets you point at your own collector.
  • Docs: a [DOCS] ticket for inference-gateway/docs (the infer stats command, telemetry.* config, an example collector config). Deferred: SQLite sink.

Record tool outcomes, token usage, and session lifecycle as append-only
JSONL under <config-dir>/metrics, and add `infer stats` to aggregate them:
tool calls by name (count, failure rate, p50/p95), tokens + cost by model,
and sessions by mode.

- internal/metrics: Recorder (O_APPEND JSONL, nil = disabled no-op),
  a ToolService decorator, and read-side aggregation + retention pruning.
- Taps: the tool decorator wraps the container tool service (covers chat
  and the headless subprocess); one usage tap in storeIterationMetrics
  (the shared #835 accumulator); full session start/end lifecycle in the
  chat and headless commands.
- Config: metrics.enabled (default true) + retention_days.
- Local-only: no prompt/response content, nothing sent anywhere.

The event model mirrors the ecosystem's OTel GenAI / infer.* metrics
(gateway otel/, infer-action src/otel.ts) so the OTLP exporter this
unblocks is a 1:1 projection; the enum values are pinned by a test.

Tests sandbox HOME so the recorder never touches the real ~/.infer.

Closes #841
@edenreich
edenreich requested a review from a team as a code owner July 12, 2026 19:48
Add a second sink on the recorder's event stream that maps events onto
OpenTelemetry GenAI/infer.* instruments and pushes them to a collector,
alongside the local JSONL. Opt-in and additive: active only when
metrics.otlp.endpoint (or OTEL_EXPORTER_OTLP_ENDPOINT) is set; when unset,
no otel SDK is initialized and nothing leaves the machine. `infer stats`
keeps reading the local JSONL in both modes.

- internal/metrics: the Recorder fans events to sinks; otlpSink uses the
  otel-go SDK meter provider + periodic reader, flushing on shutdown.
  Instrument names/attributes match the gateway's OTLP ingest and
  infer-action (gen_ai.client.token.usage, gen_ai.execute_tool.duration,
  infer.agent.tool.calls, infer.agent.runs, infer.client.cost).
- Config: metrics.otlp.{endpoint, headers, interval}.
- Exporter init/export failures are logged and dropped, never affecting
  the CLI; a ManualReader test pins the metric mapping.

Closes #842
@edenreich edenreich changed the title feat(metrics): local metrics recorder and infer stats feat(metrics): metrics recorder, infer stats, and opt-in OTLP export Jul 12, 2026
…ution mode

Rename metrics -> telemetry (package, config block, ~/.infer/telemetry dir) since
metrics is one part of the concept - traces/logs may follow. Drop the custom
compact JSONL and the event->OTLP mapping layer: there is now one instrumentation
path. Events are recorded into OpenTelemetry SDK instruments and written by OTel
exporters unchanged, so the local file is the same semconv data that is exported:

- local (always, private): the SDK stdout exporter appended to a per-session file
  under ~/.infer/telemetry/ - OTLP/semconv JSON as-is, no custom naming.
- remote (opt-in): the OTLP/HTTP exporter, active only when telemetry.otlp.endpoint
  (or OTEL_EXPORTER_OTLP_ENDPOINT) is set.

Both use delta temporality - what the gateway ingest requires, and what makes the
local files trivially summable by `infer stats`. service.version and
infer.execution.mode (interactive vs headless) are stamped on every metric via
the resource, answering "which version" and "how are they using it".

`infer stats` parses the local OTLP/stdout files.
@edenreich edenreich changed the title feat(metrics): metrics recorder, infer stats, and opt-in OTLP export feat(telemetry): OpenTelemetry recorder, infer stats, and OTLP export Jul 12, 2026
…ult 7-day retention

Old telemetry files now move to a telemetry/archive/ subdir on `infer stats`
rather than being deleted, so history is retained. Aggregate's non-recursive
glob already skips archive/, so archived data leaves the active stats without
being re-processed. Default retention_days lowered 90 -> 7.
The telemetry resource hardcoded service.name/version/execution.mode and
ignored the standard OTel env vars, and the OTLP reader always passed an empty
headers map that clobbered OTEL_EXPORTER_OTLP_HEADERS. Now:

- newResource merges OTEL_SERVICE_NAME + OTEL_RESOURCE_ATTRIBUTES on top of the
  built-in attrs (env wins), so a caller can tag runs without a code change.
- newOTLPReader only sets WithHeaders when headers are configured, letting
  OTEL_EXPORTER_OTLP_HEADERS flow through for pure env-driven consumers.

This makes the CLI the single, env-configurable telemetry engine: downstream
consumers (infer-action, CI) set OTEL_* env vars and run infer rather than
re-implementing export.
Comment thread internal/container/container.go Resolved
Comment thread internal/telemetry/recorder_test.go Resolved
…telemetry

The recorder wrote telemetry under the resolved config dir while `infer stats`
read a bare relative `.infer/telemetry`, so stats run from a different directory
than the recording session found nothing ("No telemetry recorded yet.") and
telemetry fragmented per project. Telemetry is user-global, so pin both the
writer and reader to a single userspace store via config.TelemetryDir()
(~/.infer/telemetry), independent of cwd or any project-local .infer.
@edenreich
edenreich merged commit b6bfb49 into main Jul 12, 2026
1 check passed
@edenreich
edenreich deleted the feat/metrics-recorder-stats branch July 12, 2026 22:44
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.145.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jul 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] OTLP metrics exporter [FEATURE] Metrics recorder and infer stats: tool outcomes, tokens, sessions

1 participant