Skip to content

feat(telemetry): add infer traces command and /traces shortcut - #908

Merged
edenreich merged 1 commit into
mainfrom
feat/traces-viewer
Jul 13, 2026
Merged

edenreich merged 1 commit into
mainfrom
feat/traces-viewer

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

Summary

Closes #903.

PR #901 (towards #893) records the traces signal locally — every session writes a per-session ~/.infer/telemetry/<session>-traces.jsonl with a session root span, chat <model> spans per LLM turn, and execute_tool <name> spans per tool call — but nothing in the CLI rendered them. This adds a local span-tree viewer, paired the same way infer stats / /stats are.

What's included

  • infer traces [session-id] renders the span tree of a session (root → LLM turns → tool calls) with per-span durations from the local trace file; with no argument it picks the most recent session. --list enumerates sessions that have trace files, --format json emits the tree as structured output (span names, start times, fractional-ms durations, attributes, children).
  • /traces [session-id] chat shortcut renders the same tree inside the chat TUI, colored from the static CLI palette (dim connectors, accent durations, red error markers). The output is deliberately plain text rather than markdown: the chat markdown renderer intentionally bypasses glamour for content containing box-drawing characters, so fenced/heading markup would display raw.
  • Error visibility: spans with error status or an error.type attribute carry a trailing [error: <type>] marker, rendered red in the CLI.
  • Live sessions: spans export as they end, so a running session's file has no session root yet. Orphan spans sharing a missing parent are grouped under a synthetic session (in progress) root, so mid-session /traces still renders a proper tree instead of a flat list.
  • Duration fidelity: durations are kept at microsecond precision (162µs, 41ms, 3.4s, 1m32s) instead of truncating sub-millisecond tool spans to 0ms.
session (standard, success)                38.8s
├── chat ollama_cloud/deepseek-v4-flash     3.4s
├── execute_tool Read                      162µs
├── execute_tool Read                      137µs
╰── chat ollama_cloud/deepseek-v4-flash     8.1s

Implementation notes

  • The tree is rendered via charm.land/lipgloss/v2/tree with a TreeStyle of lipgloss.Style values; the zero value renders plain, which is what the shortcut's non-TTY-safe paths rely on. Widths are measured with lipgloss.Width and durations are right-aligned across the whole tree.
  • LoadTraceTree links spans purely by Parent.SpanID, order-independent, so once subprocess span ingestion lands ([FEATURE] W3C trace context and baggage propagation to subprocesses, span ingestion via OTLP #904) child-process spans appear under their tool span with no viewer changes.
  • Read-only over the existing stdouttrace stub format already exercised by internal/telemetry/tracer_test.go; works fully offline, no OTLP endpoint required, and displays no prompt/response content beyond existing span names/attributes.

Testing

  • Table-driven unit tests for tree assembly (sorting, orphan grouping, malformed lines, error-status precedence), session listing, and duration formatting, plus an end-to-end test that records a real session → LLM turn → failing tool trace through the Recorder and asserts the loaded tree, keeping the viewer in lock-step with the writer's format.
  • Shortcut tests for empty store, default-to-latest, explicit session id, and unknown session.
  • Verified live in the chat TUI (tmux + mock gateway) and against real recorded sessions via the built binary.

Follow-ups

Local span-tree viewer over the per-session -traces.jsonl files:

- infer traces [session-id] renders the session span tree (root -> LLM
  turns -> tool calls) with per-span durations; defaults to the most
  recent session, --list enumerates sessions, --format json emits the
  tree as structured output
- /traces [session-id] chat shortcut renders the same tree, colored
  from the static CLI palette
- spans with error status / error.type carry an [error: <type>] marker
- live sessions (root span not yet exported) group orphan spans under
  a synthetic 'session (in progress)' root
- tree rendered via lipgloss/v2/tree; sub-ms spans show microseconds
@edenreich
edenreich requested a review from a team as a code owner July 13, 2026 22:14
@edenreich edenreich added this to 2026 Jul 13, 2026
@edenreich edenreich moved this to QA in 2026 Jul 13, 2026
@edenreich
edenreich merged commit 8000a4b into main Jul 13, 2026
1 check passed
@edenreich
edenreich deleted the feat/traces-viewer branch July 13, 2026 22:22
@edenreich edenreich moved this from QA to Done in 2026 Jul 13, 2026
edenreich added a commit that referenced this pull request Jul 16, 2026
…st child spans via OTLP (#909)

## Summary

Closes #904.

Today a bash command, skill script, or subagent is one opaque
`execute_tool` span with a total duration only. This PR makes subprocess
timing cooperative and open-standard: the CLI propagates context out
using pure W3C conventions, and children report spans back via standard
OTLP. No proprietary formats or env vars are introduced, so anything
already instrumented with an OTel SDK (or `otel-cli`) integrates with
zero custom code. Local storage remains the default sink; a remote OTLP
collector stays opt-in via the existing `telemetry.otlp.endpoint`
config.

**Context out (W3C).** The telemetry tool-span decorator computes
`TRACEPARENT`/`TRACESTATE` (from the live `execute_tool` span, via the
standard OTel `propagation.TraceContext` propagator) and `BAGGAGE`
(`infer.session.id`, `infer.tool.call.id` — no secrets) once per tool
span and carries the result on the context. The Bash tool sets it on the
child env (one assignment covers foreground, streaming, and detached —
they share the same `exec.Cmd`), and headless subagents get it through
`subagentExtraEnv`. When telemetry is disabled the decorator is absent,
so children get no trace env at all. Skills run through the Bash tool
and are covered transitively.

**Spans in (OTLP).** The OTLP sink for children is resolved in
`Recorder.ChildEnv`: a config-file endpoint is passed through explicitly
as `OTEL_EXPORTER_OTLP_ENDPOINT`/`OTEL_EXPORTER_OTLP_HEADERS`; an
env-configured endpoint is simply inherited; and with no endpoint at
all, a lazy ephemeral loopback OTLP/HTTP receiver accepts `POST
/v1/traces` (protobuf) and persists each span into the per-session local
trace file in the stdouttrace stub shape the `/traces` viewer (#903 /
#908) reads. Defensive limits: 4 MiB per request, 5000 spans per
session, always responds 200 — receiver failures never fail the tool. A
`lockedWriter` shared between the stdouttrace exporter and the receiver
serializes trace-file writes, eliminating interleaving by construction.

**Subagent stitching.** `StartSession` now extracts an inherited
`TRACEPARENT`/`TRACESTATE` from the environment (standard extract; no
env means unchanged behavior), so a subagent's session span parents
under the caller's `execute_tool Agent` span — one cross-process trace.
Since the parent points the child at its loopback receiver, the child's
existing OTLP export path lights up with zero child-side code and its
spans land in the parent's session file. Verified end to end against the
mock gateway:

```text
session (standard, success)            152ms
|-- chat openai/gpt-4o                   5ms
|-- execute_tool Agent                  89ms
|   `-- session (readonly, success)     52ms
|       |-- chat openai/gpt-4o           5ms
|       `-- chat openai/gpt-4o          13ms
`-- chat openai/gpt-4o                  12ms
```

**A2A remote servers.** All six adk client construction sites now use
`telemetry.NewA2AClient`, which wraps the HTTP transport with a
RoundTripper injecting `traceparent`/`tracestate`/`baggage` headers from
the request context. This is context-out only: whether a remote agent
records spans and where they go is its business (shared-collector
scenario); its spans do not land in our local store.

No new config keys and no new go.mod modules: `otel/propagation` and
`otel/baggage` live in the already-required `go.opentelemetry.io/otel`
root module; `go.opentelemetry.io/proto/otlp` and
`google.golang.org/protobuf` merely moved from indirect to direct.

## Known limitations

- Interactive (tmux-pane) subagents do not receive the trace env; only
headless subagents stitch. Deliberate: an interactive pane is a
user-driven `infer chat` REPL without completion semantics.
- Detached/background bash children that outlive the parent process lose
late spans silently once the parent's receiver goes away, consistent
with "receiver failures never fail the tool".
- A subagent's spans exist both in its own session file and in the
parent's (via the receiver). Nothing double-counts: the viewer is
per-session-file, and `infer stats` reads metrics files, which are
untouched.

## Testing

- `internal/telemetry/propagation_test.go`: `ChildEnv` matrix (nil
recorder, no span, loopback default, config endpoint passthrough,
env-endpoint inheritance), baggage members, header injection on traced
vs untraced requests.
- `internal/telemetry/receiver_test.go`: real OTLP protobuf export
ingested and nested under the tool span by `LoadTraceTree`; garbage
payloads and `/v1/metrics` accepted and dropped; session span cap
enforced.
- `recorder` test: inherited `TRACEPARENT` becomes the session span's
parent; unset keeps a zero parent.
- `bash` tool test: trace env present in the child exactly when the
context carries it.
- Full suite, `go test -race` on the touched packages, and golangci-lint
all pass. Manual end-to-end run against the mock gateway shown above.

## Cross-repo impact

Docs only: follow-up `[DOCS]` issue filed against inference-gateway/docs
to document the propagation contract with otel-cli and OTel SDK
examples. No schema, gateway, or operator changes — all env vars used
are standard OTel/W3C ones.

---------

Co-authored-by: inference-gateway-maintainer[bot] <246577062+inference-gateway-maintainer[bot]@users.noreply.github.com>
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.147.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 16, 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

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

[FEATURE] Add /traces shortcut and infer traces command (local span-tree viewer)

1 participant