Skip to content

Design least-invasive OTEL GenAI observability for agents (zero/minimal code changes) #667

Closed as not planned

Description

@Ladas

Summary

Design and evaluate approaches for OTEL GenAI trace observability (Agent + LLM spans visible in MLflow/Phoenix) that require minimal or zero changes to agent code, while passing the same E2E tests introduced in PR #569.

Currently, PR kagenti/agent-examples#114 adds ~551 lines of observability.py to the weather agent with middleware, explicit MLflow/OpenInference/GenAI attribute setting. This works but is invasive - every agent needs this boilerplate.

Goal: Find infrastructure-level solutions where the platform handles observability, not individual agents.

The Root Span Problem

graph TD
    subgraph "What MLflow Needs"
        RS[Root Span: invoke_agent weather-assistant]
        RS -->|mlflow.spanInputs| INPUT[User Input]
        RS -->|mlflow.spanOutputs| OUTPUT[Agent Response]
        RS -->|mlflow.traceName| NAME[weather-assistant]
        RS -->|gen_ai.conversation.id| SESSION[Session ID]
        RS --> LC[LangChain Spans]
        LC --> LLM[LLM Call Spans]
        LLM -->|gen_ai.usage.input_tokens| TOKENS[Token Counts]
        LC --> TOOL[Tool Call Spans]
    end
Loading

The root span is the main challenge:

  • MLflow reads mlflow.spanInputs/mlflow.spanOutputs from the ROOT span only
  • Auto-instrumented LLM metrics (tokens) come from nested spans - this works fine
  • If root span starts inside agent = agent needs custom code (current approach)
  • If root span starts outside agent (proxy) = challenge is connecting it to agent's internal traces
  • OTEL Collector cannot create new spans - only modify existing ones

Research Findings

OTEL Collector Capabilities (Verified)

Capability Supported?
Create new spans NO - requires custom processor/connector
Modify span attributes YES - transform processor
Modify parent_span_id (static) YES - OTTL
Dynamic reparenting (cross-span) NO - no cross-span awareness
Promote span attrs to resource YES - groupbyattrs processor
Copy attributes between spans NO - requires custom processor

AuthBridge ext_proc (Existing Infrastructure)

  • Go-based gRPC server at localhost:9090 inside agent pods
  • Handles inbound JWT validation + outbound token exchange
  • Currently processes headers only (request_body_mode: NONE)
  • No OTEL instrumentation - only basic logging
  • Auto-injected via webhook when kagenti.io/inject=enabled

Istio Waypoint

  • Native tracing creates HTTP-level spans but cannot parse request bodies
  • WasmPlugin is supported but requires Wasm development
  • ext_proc requires Envoy Gateway as waypoint (additional component)

Approaches to Evaluate

Approach A: AuthBridge ext_proc Root Span (Zero Agent Changes) ⭐

sequenceDiagram
    participant Client
    participant Envoy as Envoy Sidecar
    participant ExtProc as ext_proc<br/>(AuthBridge + OTEL)
    participant Agent as Agent Code
    participant LLM as LLM Provider
    participant Collector as OTEL Collector
    participant MLflow

    Client->>Envoy: A2A JSON-RPC Request
    Envoy->>ExtProc: Request Headers + Body
    Note over ExtProc: Parse A2A JSON-RPC<br/>Extract user input, context_id
    Note over ExtProc: Create root span:<br/>invoke_agent weather-assistant
    Note over ExtProc: Set traceparent header
    ExtProc->>Envoy: Modified headers (+ traceparent)
    Envoy->>Agent: Request (with trace context)
    Agent->>LLM: LLM call (auto-instrumented)
    Note over Agent: LangChain/OpenAI spans<br/>inherit trace context
    LLM-->>Agent: Response + token counts
    Agent-->>Envoy: A2A Response
    Envoy->>ExtProc: Response Headers + Body
    Note over ExtProc: Parse response<br/>Set mlflow.spanOutputs on root span
    ExtProc-->>Envoy: OK
    Envoy-->>Client: Response

    ExtProc->>Collector: Root span with all MLflow attrs
    Agent->>Collector: Nested LLM/Tool spans
    Collector->>MLflow: Complete trace tree
Loading

What changes:

  • Extend AuthBridge Go ext_proc to create OTEL root spans
  • Change Envoy config: request_body_mode: BUFFERED, response_body_mode: BUFFERED
  • Add OTEL SDK to Go ext_proc code

Agent needs only:

  • OTEL SDK setup (TracerProvider + OTLP exporter) - standard boilerplate
  • Auto-instrumentation libraries (LangChain, OpenAI) - already needed
  • W3C Trace Context propagation configured
  • Zero custom observability code

Why this works:

  • AuthBridge already intercepts ALL agent traffic via iptables
  • ext_proc can access request/response bodies with BUFFERED mode
  • W3C traceparent header injection ensures agent spans become children
  • Root span lives in ext_proc with full MLflow/OpenInference/GenAI attributes

Approach B: Minimal Agent Boilerplate + Collector Enrichment (Minimal Changes)

Since OTEL Collector cannot create spans, agent needs ONE root span. But make it as simple as possible:

# ENTIRE agent observability code (~15 lines)
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)

# Middleware: just create named root span, nothing else
tracer = trace.get_tracer("agent")
async def middleware(request, call_next):
    with tracer.start_as_current_span("invoke_agent my-agent"):
        return await call_next(request)

OTEL Collector does ALL the enrichment:

transform/genai_to_mlflow:
  trace_statements:
    - context: span
      statements:
        - set(attributes["mlflow.spanType"], "AGENT") where IsRootSpan()
        - set(attributes["mlflow.traceName"], resource.attributes["service.name"]) where IsRootSpan()
        - set(attributes["mlflow.source"], resource.attributes["service.name"]) where IsRootSpan()
        # ... etc

Limitations:

  • Agent still needs ~15 lines of boilerplate (TracerProvider + middleware)
  • No input/output capture without body parsing (collector can't access HTTP body)
  • Session tracking requires agent to set gen_ai.conversation.id

Approach C: Envoy Sidecar + Correlation ID (From Team Discussion)

graph LR
    subgraph "Agent Pod"
        E[Envoy Sidecar] -->|x-request-id| A[Agent]
        A -->|x-request-id| E
    end
    E -->|Independent spans<br/>with correlation ID| OC[OTEL Collector]
    OC -->|Post-hoc<br/>reconstruction| J[Jaeger/Tempo]
Loading
  • Envoy sidecars inject trust metadata headers (caller-id, target, etc.)
  • Shared correlation ID propagated through all hops
  • Reconstruct causal chain post-hoc using temporal backtracking

Assessment: NOT viable for MLflow E2E tests

  • MLflow expects real parent-child trace tree, not post-hoc correlation
  • Temporal backtracking adds complexity and latency
  • Better suited for delegation/provenance tracking (complementary use case)
  • Could complement Approach A for trust chain visibility

Approach D: Istio WasmPlugin on Waypoint (Zero Agent Changes, Higher Effort)

  • Write a Wasm plugin (Rust/Go) for waypoint proxy
  • Plugin buffers A2A request/response bodies
  • Creates OTEL spans with all required attributes
  • Exports to OTEL Collector via HTTP

Assessment: Medium viability

  • WasmPlugin is officially supported on waypoints
  • Wasm development is more complex than extending Go ext_proc
  • Body buffering in Wasm has performance implications
  • Less practical than Approach A since AuthBridge already exists

Approach E: Agent Middleware (Current Baseline from PR 114)

The current working approach for reference:

  • ~551 lines of observability.py in agent code
  • Middleware creates root span with all attributes
  • Agent code sets input/output on root span
  • Auto-instrumentation for LangChain + OpenAI
  • Most invasive but most reliable

Success Criteria

Each approach must pass the MLflow E2E tests from test_mlflow_traces.py:

  • TestWeatherAgentTracesInMLflow - traces exist, identified by service.name
  • TestGenAITracesInMLflow - LLM spans with tree structure
  • TestMLflowTraceMetadata - request_id, timing, state
  • TestSessionTracking - gen_ai.conversation.id present
  • TestRootSpanAttributes - mlflow.spanInputs/Outputs, user, traceName, version, runName + OpenInference input/output.value + GenAI conversation.id, agent.name
  • TestTokenUsageVerification - gen_ai.usage.input/output_tokens on LLM spans
  • TestToolCallSpanAttributes - tool name, input/output, span kind
  • TestErrorSpanValidation - error status and exception details

Implementation Plan

  1. Create worktree per approach from upstream/main
  2. Each approach gets a draft PR with implementation + documentation
  3. Run E2E tests (TDD loop) against each approach
  4. Compare results - which tests pass, performance impact, complexity
  5. Document findings - tradeoffs, recommendations

Related

Activity

  1. added
    enhancement
    on Feb 12, 2026
  2. Ladas commented on Feb 12, 2026

    @Ladas
    ContributorAuthor

    Draft PRs Created

    Each approach has a worktree and draft PR with a design document:

    Approach PR Worktree Agent Changes MLflow Tests
    A: AuthBridge ext_proc #668 .worktrees/otel-authbridge-approach Zero Expected: PASS
    B: Minimal Agent + Collector #669 .worktrees/otel-minimal-agent ~50 lines Expected: MOSTLY PASS
    C: Correlation Sidecar #670 .worktrees/otel-correlation-sidecar Zero NOT targeting (different use case)
    E: Baseline (PR 114) agent-examples#114 existing ~551 lines PASS (verified)

    Research Findings Summary

    OTEL Collector Limitations (Verified)

    • Cannot create new spans — only modify existing ones
    • Cannot copy attributes between spans — no cross-span awareness
    • CAN modify individual span attributes via transform processor
    • CAN detect root spans via IsRootSpan() (v0.104.0+)
    • CAN promote span attrs to resource via groupbyattrs

    AuthBridge Infrastructure (Existing)

    • Go-based ext_proc gRPC server already intercepts all agent traffic
    • Currently: headers only, no OTEL, no body parsing
    • Extension: add body buffering + A2A JSON-RPC parsing + OTEL span creation

    Istio Waypoint (Alternative to AuthBridge)

    • WasmPlugin supported but requires Wasm development
    • ext_proc requires Envoy Gateway (additional component)
    • Native tracing creates HTTP spans but cannot parse bodies

    Next Steps

    1. Parametrize MLflow E2E tests to run against multiple agent variants (each approach deploys differently)
    2. Implement Approach A (most promising zero-change path) — extend AuthBridge Go code
    3. Implement Approach B (simplest agent-side path) — minimal middleware + collector enrichment
    4. Run E2E tests via TDD loop on HyperShift
    5. Compare results across approaches
  3. Ladas commented on Feb 12, 2026

    @Ladas
    ContributorAuthor

    Implementation Complete - All CI Green

    All three draft PRs are implemented, pushed, and passing CI (lint, build, DCO, security, Deploy & Test):

    PR Status

    PR Approach CI Commits Key Files
    #668 A: AuthBridge ext_proc ✅ All pass 3 Go OTEL tracing (otel_tracing.go, process_with_otel.go), Envoy body buffering config, agent-otel ConfigMap
    #669 B: Minimal Agent + Collector ✅ All pass 3 observability_minimal.py (50 lines), transform/agent_enrichment in otel-collector.yaml (15 OTTL statements)
    #670 C: Correlation Sidecar ✅ All pass 2 Design doc only (complementary, not standalone for MLflow)

    Shared Across All PRs

    • Parametrized E2E tests via AGENT_OBSERVABILITY_VARIANT env var + VariantProfile dataclass
    • Supports variants: baseline, minimal, authbridge, none
    • Tests assert/skip based on what each variant produces

    Comparison: Agent Code Required

    Approach Lines of Agent Code What Agent Sets What Infrastructure Sets
    E: Baseline (PR 114) ~551 lines Everything (mlflow., OI., GenAI.*) Nothing
    B: Minimal + Collector ~50 lines input.value, output.value, gen_ai.agent.name, gen_ai.conversation.id mlflow.*, openinference.span.kind, llm.token_count.*, etc.
    A: AuthBridge ext_proc 0 lines Auto-instrumentation only (LangChain, OpenAI) Everything (root span + all attributes)
    C: Correlation Sidecar 0 lines Nothing HTTP-level spans only (no body content)

    Next Steps: TDD on Cluster

    To validate each approach passes the MLflow E2E tests, deploy to a cluster and run:

    # For each approach, set the variant and run
    AGENT_OBSERVABILITY_VARIANT=minimal pytest -m observability -v
    AGENT_OBSERVABILITY_VARIANT=authbridge pytest -m observability -v

    This requires:

    1. Deploying the weather agent with each approach's instrumentation
    2. Running conversation tests (Phase 1) to generate traces
    3. Running observability tests (Phase 2) to validate traces in MLflow
  4. 76 remaining items

  5. esnible commented on Feb 19, 2026

    @esnible
    Member

    Note that Kuadrant/mcp-gateway#595 added observability to the MCP Gateway.

    I am surprised we needed 551 lines to add observability. Kagenti already adds OTEL_EXPORTER_OTLP_ENDPOINT to the agents, and I see deep traces from the agent already. I have viewed these traces in both Phoenix and with Tempo (using Jaeger UI).

  6. evaline-ju commented on Feb 19, 2026

    @evaline-ju
    Contributor

    Note that Kuadrant/mcp-gateway#595 added observability to the MCP Gateway.

    fyi I've tried this out with Kagenti - we'll need to connect some dots here to bring this in, starting with #616 (I know this is in progress)

  7. esnible commented on Apr 14, 2026

    @esnible
    Member

    @ilya-kolchinsky are you working on this?

  8. ilya-kolchinsky commented on Apr 15, 2026

    @ilya-kolchinsky
    Contributor

    @esnible I have a non-Kagenti prototype here. Got some pushback on it (both internally and from the Kagenti team) due to lack of support of Go and compiled languages in general. This gap is real, but unfortunately very hard to address due to the very rudimentary support of the above by the OTel operator. So for now this PoC has been put on the shelf.
    If there is still interest in this direction, and if you believe the lack of Go support is not a dealbreaker, I'm open to further discussing this and contributing the feature as a Kagenti operator extension.

  9. github-actions commented on Jul 22, 2026

    @github-actions

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. If this issue is still relevant, please comment or remove the stale label.

  10. github-actions commented on Aug 5, 2026

    @github-actions

    This issue was closed because it has been stale for 14 days with no activity. Feel free to reopen if this is still relevant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Observabilityenhancementstale

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions