πŸ“‘ OpenTelemetry β€” Trace Format Master Guide

OTel Fundamentals Β· OTLP Wire Format Β· Hyperscaler Differences (AWS/GCP/Azure) Β· Trace Parsing Β· Tabular Conversion Β· Normalization Β· Anomaly Detection

What Is OpenTelemetry and Why Does the Format Matter?
OTel is the open standard for telemetry data. But every hyperscaler adds its own twist β€” different field names, ID formats, timestamp units, and attribute namespaces. Understanding the format is prerequisite to parsing and comparing traces across systems.

πŸ—οΈ The OTel Signal Stack

πŸ“‘
Traces
Distributed request flows. A trace = tree of spans. Each span = one unit of work (LLM call, DB query, HTTP request). This guide's focus.
πŸ“Š
Metrics
Numerical measurements over time. Counters, gauges, histograms. Token counts, latencies, error rates.
πŸ“‹
Logs
Structured event records. Correlated to traces via trace_id + span_id. OTel unifies all three under one SDK.

πŸ”„ The OTel Pipeline β€” Data Flow

πŸ“± App
+ OTel SDK
β†’
πŸ“‘ OTLP
gRPC/HTTP
β†’
πŸ”§ OTel
Collector
β†’
πŸ” Process
Filter/Batch
β†’
☁️ Backend
Exporter
β†’
πŸ“Š Jaeger/
Tempo/X-Ray
πŸ’‘
The OTel Collector is the critical middleware layer β€” it receives traces in OTLP, processes them (filter, batch, enrich, redact PII), then exports to one or many backends simultaneously. This is where format translation happens.

🌐 Why Hyperscaler Formats Differ

All three major clouds now support OTLP, but each evolved from a pre-OTel proprietary format. The differences are legacy residue β€” and they matter when you're:

  • β†’
    Migrating between cloud providers
  • β†’
    Federating traces from multi-cloud agents
  • β†’
    Parsing trace exports programmatically
  • β†’
    Building cross-cloud observability dashboards
  • β†’
    Comparing LLM agent traces across platforms
CloudLegacy FormatOTel Status 2025
☁️ AWSX-Ray JSONOTLP via ADOT; own trace ID format still used internally
πŸ”΅ AzureApp Insights SDKAzure Monitor OTel Distro; stores spans as requests/dependencies
🟑 GCPOpenCensusNative OTLP ingestion since Sep 2025; OTel is the native path
🌐 Self-hostedJaeger/ZipkinPure OTLP; closest to the spec
πŸ“ The OTLP Wire Format β€” What's Actually Transmitted
OTLP is the binary protocol (Protocol Buffers over gRPC or HTTP) that carries telemetry data. Understanding the structure lets you parse any trace export correctly.

πŸ›οΈ The Three-Level Hierarchy

Every OTLP trace export nests data in three levels. This hierarchy is the key to parsing β€” you need to unwrap all three to get to individual spans.

// OTLP ExportTraceServiceRequest β€” the top-level envelope { "resourceSpans": [ // Level 1: one entry per SERVICE { "resource": { // Describes the producing entity "attributes": [ {"key": "service.name", "value": {"stringValue": "payment-service"}}, {"key": "service.version", "value": {"stringValue": "2.1.0"}}, {"key": "deployment.environment", "value": {"stringValue": "production"}} ] }, "scopeSpans": [ // Level 2: one entry per INSTRUMENTATION LIBRARY { "scope": {"name": "opentelemetry.instrumentation.anthropic", "version": "0.4.0"}, "spans": [ // Level 3: the actual SPANS { "traceId": "5b8aa5a2d2c872e8321cf37308d69df2", // 16 bytes hex = 32 chars "spanId": "051581bf3cb55c13", // 8 bytes hex = 16 chars "parentSpanId": "b7ad6b7169203331", // absent if root span "name": "anthropic.messages.create", "kind": 3, // 1=Internal 2=Server 3=Client 4=Producer 5=Consumer "startTimeUnixNano": "1696282800000000000", // nanoseconds since Unix epoch "endTimeUnixNano": "1696282802341000000", "attributes": [ {"key": "gen_ai.system", "value": {"stringValue": "anthropic"}}, {"key": "gen_ai.request.model", "value": {"stringValue": "claude-sonnet-4-6"}}, {"key": "gen_ai.usage.input_tokens", "value": {"intValue": "1240"}}, {"key": "gen_ai.usage.output_tokens", "value": {"intValue": "387"}}, {"key": "http.status_code", "value": {"intValue": "200"}} ], "status": {"code": 1}, // 0=Unset 1=Ok 2=Error "events": [], "links": [] } ] } ] } ] }

⏱️ Timestamp Gotcha β€” Nanoseconds!

# OTLP uses NANOSECONDS since Unix epoch # This trips up almost everyone the first time raw_nano = "1696282800000000000" # what OTLP gives you # Wrong β€” treating as milliseconds import datetime wrong = datetime.datetime.fromtimestamp(int(raw_nano)) # β†’ datetime(55696, 11, 15) ← year 55696! # Correct β€” divide by 1e9 to get seconds correct = datetime.datetime.fromtimestamp( int(raw_nano) / 1e9, tz=datetime.timezone.utc ) # β†’ datetime(2023, 10, 2, 21, 0, 0) # Duration from two nanosecond timestamps duration_ms = (int(end_nano) - int(start_nano)) / 1e6

πŸ”‘ Attribute Value Types

# OTLP wraps every value in a type envelope # You must check the type key before extracting def extract_value(av: dict) -> any: v = av.get("value", {}) if "stringValue" in v: return v["stringValue"] elif "intValue" in v: return int(v["intValue"]) elif "doubleValue" in v: return float(v["doubleValue"]) elif "boolValue" in v: return v["boolValue"] elif "arrayValue" in v: return [extract_value({"value": i}) for i in v["arrayValue"]["values"]] elif "kvlistValue" in v: return {kv["key"]: extract_value({"value": kv["value"]}) for kv in v["kvlistValue"]["values"]} return None # ⚠️ intValue is a STRING in JSON OTLP (protobuf int64 quirk) # Always int() it before arithmetic
πŸ”¬ Span Anatomy β€” Every Field Explained
A span is the atomic unit of a trace. Knowing what every field means is the foundation for reading, comparing, and parsing traces across any platform.

πŸ“‹ Complete Span Field Reference

FieldTypeDescriptionGotcha
trace_idhex string16-byte unique identifier for the whole distributed trace. All spans in one transaction share this.AWS X-Ray uses a different format: 1-{hex8}-{hex24}
span_idhex string8-byte identifier unique within a trace. Links parent β†’ child spans.Absent parent_span_id = root span
parent_span_idhex stringThe span_id of the parent span. Defines the tree structure.Missing/empty = root (no parent)
namestringHuman-readable operation name. Should be low-cardinality (no IDs in names).High-cardinality names explode storage
kindenum int1=Internal, 2=Server, 3=Client, 4=Producer, 5=ConsumerMost LLM spans are kind=3 (Client)
start_time_unix_nanouint64Start timestamp in nanoseconds since Unix epoch.Divide by 1e9 for seconds, 1e6 for ms
end_time_unix_nanouint64End timestamp. Duration = end - start (in nanos).In JSON, stored as string (int64 overflow)
attributesKeyValue[]Key-value metadata about this operation. The rich data source for analysis.Every value wrapped in type envelope β€” must unwrap
status.codeenum int0=Unset (default), 1=Ok, 2=ErrorUnset β‰  Ok. Explicitly set Ok on success.
status.messagestringHuman-readable error description. Only set when code=Error.Absent on success β€” don't error on missing
eventsEvent[]Timestamped annotations within a span (e.g., exception stack traces, checkpoints).Each event has its own attributes dict
linksLink[]References to spans in OTHER traces. Used for message queues, batch jobs.Rare but important for async patterns
resource.attributesKeyValue[]Describes the entity producing spans (service.name, host, k8s.pod, etc.)Defined at Resource level, not Span level

🏷️ GenAI Semantic Conventions β€” Standard Attribute Names for LLM Spans

OTel defines standard attribute names for AI/LLM spans. Using these makes traces portable across LangSmith, Langfuse, and any OTel-compatible backend.

# Required attributes for LLM spans { "gen_ai.system": "anthropic", # or "openai", "cohere" "gen_ai.operation.name": "chat", # or "text_completion", "embeddings" "gen_ai.request.model": "claude-sonnet-4-6", "gen_ai.request.max_tokens": 1000, "gen_ai.request.temperature": 0.7, "gen_ai.response.model": "claude-sonnet-4-6-20250514", "gen_ai.usage.input_tokens": 1240, "gen_ai.usage.output_tokens": 387, # Calculated from usage * pricing: "gen_ai.usage.input_cost": 0.00372, "gen_ai.usage.output_cost": 0.005805, }
# HTTP semantic conventions (for API calls) { "http.method": "POST", "http.url": "https://api.anthropic.com/v1/messages", "http.status_code": 200, "http.response_content_length": 4820, } # Database semantic conventions { "db.system": "postgresql", "db.name": "vector_store", "db.statement": "SELECT * FROM embeddings LIMIT 10", "db.operation": "SELECT", }
☁️ Hyperscaler Trace Formats β€” AWS vs GCP vs Azure
Same concept, different implementations. Here's exactly what each platform produces and how it differs from canonical OTLP.

πŸ”‘ The Critical Differences at a Glance

DimensionOTLP (Canonical)AWS X-RayGCP Cloud TraceAzure App Insights
Trace ID format32-char hex1-{8hex}-{24hex} (timestamp prefix)32-char hex (OTLP)W3C format
Timestamp unitnanosecondsseconds (float)nanosecondsmilliseconds (ISO 8601)
Span β†’ table mappingspans[]segments / subsegmentsspansrequests + dependencies (2 tables!)
Attributes namespaceOTEL semconv (gen_ai.*)AWS-specific (aws.*, xray.*)OTLP native (since Sep 2025)App Insights SDK fields
Status fieldstatus.code (0/1/2)fault / error / throttle booleansstatus.code (OTLP)success (bool) + resultCode
Parent relationshipparent_span_idparent_id on subsegmentparent_span_id (OTLP)operation_ParentId
Context propagationW3C traceparent headerX-Amzn-Trace-Id header (also W3C now)W3C traceparent headerW3C traceparent header
Export formatOTLP/gRPC, OTLP/HTTPX-Ray API JSONOTLP (native since 2025)Breeze protocol β†’ Log Analytics

🟠 AWS X-Ray Format

// X-Ray Segment (β‰ˆ root span) { "trace_id": "1-67891233-abcdef012345678912345678", // ↑ format: 1-{epoch8hex}-{24hex} // epoch component = creation time "id": "53995c3f42cd8ad8", // 16-char hex (β‰ˆ span_id) "name": "payment-service", "start_time": 1696282800.123, // float seconds! "end_time": 1696282802.341, "fault": false, // 5xx error "error": false, // 4xx error "throttle": false,// 429 error "http": { "request": {"method":"POST"}, "response":{"status":200} }, "subsegments": [...] // β‰ˆ child spans }

🟑 GCP Cloud Trace (OTLP native)

// GCP now uses OTLP natively (Sep 2025) // This is almost identical to canonical OTLP { "name": "projects/my-project/traces/5b8aa.../spans/051581...", // ↑ resource path format is GCP-specific "spanId": "051581bf3cb55c13", "parentSpanId": "b7ad6b7169203331", "displayName": { // truncated string type "value": "anthropic.messages.create", "truncatedByteCount": 0 }, "startTime": "2023-10-02T21:00:00.000Z", // RFC3339 "endTime": "2023-10-02T21:00:02.341Z", "attributes": { "attributeMap": { // note: map not array! "gen_ai.system": {"stringValue":{"value":"anthropic"}} } }, "status": {"code": "OK"} // string not int! }

πŸ”΅ Azure App Insights

// Azure stores spans in TWO different tables: // - "requests" table = SERVER spans (incoming) // - "dependencies" table = CLIENT spans (outgoing) { // From "requests" table (KQL: requests | ...) "operation_Id": "5b8aa5a2d2c872e8321cf37308d69df2", // ↑ = trace_id (different field name!) "id": "|5b8aa5a2.051581bf", // ↑ = span_id (pipe-prefixed!) "operation_ParentId": "|5b8aa5a2.b7ad6b71", "timestamp": "2023-10-02T21:00:00.000Z", "duration": "00:00:02.341", // HH:MM:SS.mmm! "success": true, "resultCode": "200", "customDimensions": { // OTel attributes land here "gen_ai.system": "anthropic" } }

πŸ”„ Context Propagation Headers β€” How Traces Cross Service Boundaries

# W3C TraceContext (the standard β€” used by OTLP, GCP, Azure, modern AWS) traceparent: 00-5b8aa5a2d2c872e8321cf37308d69df2-b7ad6b7169203331-01 # ^ ^32-char trace_id ^16-char span_id ^flags (01=sampled) # AWS X-Ray header (legacy, still widely used in AWS ecosystem) X-Amzn-Trace-Id: Root=1-67891233-abcdef012345678912345678;Parent=53995c3f42cd8ad8;Sampled=1 # ↑ "Root" = trace_id in X-Ray format "Parent" = parent span_id # AWS now supports W3C format too (since Oct 2023) β€” but you may see both in the wild # When you see BOTH headers, the OTLP collector's AWS exporter converts W3C β†’ X-Ray format
⚑ Field Mapping β€” Normalizing Across Hyperscalers
The field mapping table you actually need when writing parsers or migration scripts. Every row = one concept, four different representations.

πŸ“Š Complete Field Mapping Matrix

ConceptOTLP (canonical)AWS X-RayGCP Cloud TraceAzure App Insights
Trace IDtraceId (hex32)trace_id (1-hex8-hex24)in name pathoperation_Id
Span IDspanId (hex16)id (hex16)spanIdid (|prefix.hex format)
Parent Span IDparentSpanIdparent_id on subsegmentparentSpanIdoperation_ParentId
Span namenamenamedisplayName.valuename
Start timestartTimeUnixNano (ns int)start_time (float seconds)startTime (RFC3339)timestamp (ISO 8601)
Durationend_nano - start_nanoend_time - start_time (seconds)endTime - startTimeduration (HH:MM:SS.mmm string)
Error flagstatus.code == 2fault==true OR error==truestatus.code == "ERROR"success == false
HTTP statushttp.status_code attrhttp.response.statushttp.status_code attrresultCode
Custom attrsattributes[] (KV array)metadata or annotationsattributes.attributeMap (map)customDimensions (flat dict)
Service nameresource.service.namename (segment level)resource attributecloud_RoleName
Child spansseparate spans with parentSpanIdsubsegments[] (nested)separate spansseparate rows in dep table

πŸ”§ Universal Normalization Function

def normalize_span(raw: dict, source: str) -> dict: """Convert any hyperscaler span format to a canonical flat dict.""" if source == "otlp": attrs = {kv["key"]: _extract_val(kv["value"]) for kv in raw.get("attributes", [])} start_ns = int(raw["startTimeUnixNano"]) end_ns = int(raw["endTimeUnixNano"]) return { "trace_id": raw["traceId"], "span_id": raw["spanId"], "parent_span_id": raw.get("parentSpanId"), "name": raw["name"], "start_ts": start_ns / 1e9, "duration_ms": (end_ns - start_ns) / 1e6, "status": "error" if raw.get("status",{}).get("code")==2 else "ok", "attributes": attrs, } elif source == "xray": return { "trace_id": xray_to_hex(raw["trace_id"]), # convert format "span_id": raw["id"], "parent_span_id": raw.get("parent_id"), "name": raw["name"], "start_ts": raw["start_time"], # already seconds "duration_ms": (raw["end_time"]-raw["start_time"])*1000, "status": "error" if (raw.get("fault") or raw.get("error")) else "ok", "attributes": {**raw.get("annotations",{}), **raw.get("metadata",{})}, } elif source == "azure": duration = parse_azure_duration(raw["duration"]) # HH:MM:SS.mmm return { "trace_id": raw["operation_Id"], "span_id": raw["id"].split(".")[-1], # strip |prefix. "parent_span_id": raw.get("operation_ParentId","").split(".")[-1], "name": raw["name"], "start_ts": parse_iso(raw["timestamp"]).timestamp(), "duration_ms": duration, "status": "ok" if raw.get("success") else "error", "attributes": raw.get("customDimensions", {}), }
πŸ‘“ Reading a Trace β€” What to Look For
Given a trace (from any source), here's the systematic process for understanding it β€” from the tree structure down to individual span anomalies.

🌳 Interactive Trace Waterfall β€” Click spans to inspect

← Span name Timeline (relative to trace start) Duration β†’

πŸ” Reading a Trace β€” The Systematic Process

  1. 1
    Find the root span
    No parent_span_id = root. This is the entry point β€” its duration = total trace duration.
  2. 2
    Identify any error spans
    status.code=2, fault=true, success=false. Start debugging from the deepest error.
  3. 3
    Build the parent-child tree
    Group by parent_span_id. Visualize as waterfall. Look for sequential vs parallel spans.
  4. 4
    Find the critical path
    The longest chain of sequential spans = the bottleneck. Parallelizing these = fastest win.
  1. 5
    Check token / cost attributes
    For LLM traces: sum gen_ai.usage.input_tokens + output_tokens across all spans.
  2. 6
    Look for gaps
    Time between parent start and first child start = overhead/setup. Large gap = investigate.
  3. 7
    Compare against baseline
    p50/p95/p99 latency per span name. Alert when current trace exceeds 2x p95.
  4. 8
    Correlate with logs
    Filter logs by trace_id to get the full narrative of what happened during a slow/failed span.
πŸ§ͺ

Lab 1 β€” Paste & Parse Any OTLP JSON Trace

Paste a raw OTLP JSON trace (or use the sample). The parser will unwrap all three hierarchy levels, normalize timestamps, extract attributes, detect errors, and show you the tree structure. Works with traces from any OTel-compatible system.

πŸ”¬

Lab 2 β€” Live Trace β†’ Tabular Converter

Converts any trace format to a normalized flat table ready for pandas, SQL, or Excel. Select your source format, paste the trace, and get a clean DataFrame-ready output with one row per span.

πŸ› οΈ

Lab 3 β€” Normalize & Diff Two Traces

Paste two traces (same format or different hyperscalers), normalize both to canonical form, and see a visual diff β€” which spans changed, which are new, which are slower. Perfect for comparing prod vs canary, or migrating between clouds.

Trace A (baseline)
Trace B (compare)
πŸ€–

Lab 4 β€” AI Trace Analyst (Claude reads your trace)

Paste any trace and ask Claude to analyze it. Claude will identify the critical path, flag anomalies, calculate costs, suggest optimizations, and explain what the trace is showing in plain English.

πŸ“‹ Production Snippets
Copy-paste ready. Covering the full OTel β†’ tabular pipeline.
πŸ“ OTLP JSON β†’ Flat DataFrame
"""Parse OTLP JSON trace export into a flat pandas DataFrame.
Works with traces from Jaeger, Tempo, Langfuse, LangSmith,
Langfuse v3, and any OTel-compatible backend."""
import json, pandas as pd
from datetime import datetime, timezone

def extract_value(v: dict):
    """Unwrap OTLP attribute value envelope."""
    if "stringValue"  in v: return v["stringValue"]
    if "intValue"     in v: return int(v["intValue"])   # note: string in JSON!
    if "doubleValue"  in v: return float(v["doubleValue"])
    if "boolValue"    in v: return v["boolValue"]
    if "arrayValue"   in v:
        return [extract_value(i) for i in v["arrayValue"].get("values",[])]
    if "kvlistValue"  in v:
        return {kv["key"]: extract_value(kv["value"])
                for kv in v["kvlistValue"].get("values",[])}
    return None

SPAN_KIND = {0:"UNSPECIFIED",1:"INTERNAL",2:"SERVER",3:"CLIENT",4:"PRODUCER",5:"CONSUMER"}
STATUS_CODE = {0:"UNSET",1:"OK",2:"ERROR"}

def otlp_to_dataframe(otlp_json: str | dict) -> pd.DataFrame:
    data = json.loads(otlp_json) if isinstance(otlp_json, str) else otlp_json
    rows = []

    for rs in data.get("resourceSpans", []):
        # Extract resource attributes (service name, env, etc.)
        res_attrs = {
            kv["key"]: extract_value(kv["value"])
            for kv in rs.get("resource", {}).get("attributes", [])
        }
        service = res_attrs.get("service.name", "unknown")

        for ss in rs.get("scopeSpans", []):
            scope_name = ss.get("scope", {}).get("name", "")

            for span in ss.get("spans", []):
                # Timestamps: nanoseconds β†’ datetime
                start_ns = int(span.get("startTimeUnixNano", 0))
                end_ns   = int(span.get("endTimeUnixNano",   0))
                start_dt = datetime.fromtimestamp(start_ns / 1e9, tz=timezone.utc)
                dur_ms   = (end_ns - start_ns) / 1_000_000

                # Attributes
                attrs = {
                    kv["key"]: extract_value(kv["value"])
                    for kv in span.get("attributes", [])
                }
                status_block = span.get("status", {})

                row = {
                    # Identity
                    "trace_id":       span.get("traceId"),
                    "span_id":        span.get("spanId"),
                    "parent_span_id": span.get("parentSpanId"),
                    "name":           span.get("name"),
                    # Classification
                    "kind":           SPAN_KIND.get(span.get("kind",0)),
                    "service":        service,
                    "scope":          scope_name,
                    # Timing
                    "start_time":     start_dt,
                    "duration_ms":    round(dur_ms, 3),
                    # Status
                    "status":         STATUS_CODE.get(status_block.get("code",0)),
                    "error_msg":      status_block.get("message"),
                    # LLM-specific (from GenAI semconv)
                    "llm_system":     attrs.get("gen_ai.system"),
                    "llm_model":      attrs.get("gen_ai.request.model"),
                    "input_tokens":   attrs.get("gen_ai.usage.input_tokens"),
                    "output_tokens":  attrs.get("gen_ai.usage.output_tokens"),
                    "http_status":    attrs.get("http.status_code"),
                    # Resource metadata
                    "env":            res_attrs.get("deployment.environment"),
                    "svc_version":    res_attrs.get("service.version"),
                    # All attributes (for full mode)
                    "_attrs":         attrs,
                    "_res_attrs":     res_attrs,
                }
                rows.append(row)

    df = pd.DataFrame(rows)
    # Derived columns
    if not df.empty and "input_tokens" in df.columns:
        df["total_tokens"] = df["input_tokens"].fillna(0) + df["output_tokens"].fillna(0)
        # Rough cost (claude-sonnet-4-6 pricing)
        df["est_cost_usd"] = (
            df["input_tokens"].fillna(0)  / 1_000_000 * 3.00 +
            df["output_tokens"].fillna(0) / 1_000_000 * 15.00
        ).round(6)
    return df

# Usage:
# df = otlp_to_dataframe(open("trace.json").read())
# df[["name","duration_ms","status","total_tokens","est_cost_usd"]]
🟠 AWS X-Ray β†’ Normalized Dict
"""Normalize AWS X-Ray trace segments to canonical OTLP-style dicts.

Key conversions:
  - trace_id: "1-hex8-hex24" β†’ 32-char hex
  - timestamps: float seconds β†’ unix nanoseconds
  - status: fault/error/throttle booleans β†’ status code
  - subsegments: nested dict β†’ flat list with parent_id
"""
import re
from datetime import datetime, timezone

def xray_traceid_to_hex(xray_id: str) -> str:
    """Convert '1-67891233-abcdef012345678912345678' to 32-char hex."""
    parts = xray_id.split("-")
    if len(parts) == 3 and parts[0] == "1":
        epoch_hex = parts[1]   # 8-char hex timestamp
        random_hex = parts[2]  # 24-char random hex
        return (epoch_hex + random_hex).ljust(32, "0")
    return xray_id  # already in some other format

def xray_status(segment: dict) -> str:
    if segment.get("fault"):    return "ERROR"   # 5xx
    if segment.get("error"):    return "ERROR"   # 4xx
    if segment.get("throttle"): return "ERROR"   # 429
    return "OK"

def flatten_xray_segments(segment: dict, trace_id: str, parent_id: str = None) -> list:
    """Recursively flatten X-Ray segments + subsegments into a flat span list."""
    start_s = segment.get("start_time", 0)
    end_s   = segment.get("end_time", start_s)

    http = segment.get("http", {})
    req  = http.get("request", {})
    resp = http.get("response", {})

    span = {
        "source":         "xray",
        "trace_id":       xray_traceid_to_hex(trace_id),
        "span_id":        segment.get("id"),
        "parent_span_id": parent_id,
        "name":           segment.get("name"),
        "start_time":     datetime.fromtimestamp(start_s, tz=timezone.utc),
        "duration_ms":    round((end_s - start_s) * 1000, 3),
        "status":         xray_status(segment),
        "http_method":    req.get("method"),
        "http_status":    resp.get("status"),
        "url":            req.get("url"),
        # Annotations = user-defined key-value strings
        "annotations":    segment.get("annotations", {}),
        # Metadata = arbitrary nested user data
        "metadata":       segment.get("metadata", {}),
        # AWS-specific
        "aws_region":     segment.get("aws", {}).get("region"),
        "aws_service":    segment.get("aws", {}).get("operation"),
    }

    spans = [span]
    # Recursively process subsegments (children)
    for sub in segment.get("subsegments", []):
        spans.extend(
            flatten_xray_segments(sub, trace_id, parent_id=segment["id"])
        )
    return spans

def xray_trace_to_dataframe(xray_json: str | dict):
    import json, pandas as pd
    data = json.loads(xray_json) if isinstance(xray_json, str) else xray_json

    all_spans = []
    for trace in data.get("Traces", [data]):  # handle single or batch
        tid = trace.get("Id", "unknown")
        for seg in trace.get("Segments", [trace]):
            doc = seg.get("Document", seg)
            if isinstance(doc, str):
                import json as _j
                doc = _j.loads(doc)
            all_spans.extend(flatten_xray_segments(doc, tid))

    return pd.DataFrame(all_spans)
πŸ”΅ Azure App Insights β†’ DataFrame
"""Normalize Azure App Insights telemetry to canonical form.

Azure stores spans in TWO different tables:
  - requests: SERVER spans (incoming HTTP, functions)
  - dependencies: CLIENT spans (HTTP calls, DB, LLM calls)

Both must be combined for a complete trace view.

Key conversions:
  - operation_Id β†’ trace_id
  - id: "|traceId.spanHex" β†’ strip prefix
  - duration: "HH:MM:SS.mmm" β†’ milliseconds
  - customDimensions β†’ attributes dict
"""
import re, json
import pandas as pd
from datetime import datetime, timezone, timedelta

def parse_azure_duration(duration_str: str) -> float:
    """Convert Azure duration 'HH:MM:SS.mmm' or 'D.HH:MM:SS.mmm' to ms."""
    # Format examples: "00:00:02.341" or "0.00:00:02.3410000"
    pattern = r"(?:(\d+)\.)?(\d{2}):(\d{2}):(\d{2})\.(\d+)"
    m = re.match(pattern, duration_str)
    if not m:
        return 0.0
    days  = int(m.group(1) or 0)
    hours = int(m.group(2))
    mins  = int(m.group(3))
    secs  = int(m.group(4))
    frac  = m.group(5)
    ms    = float("0." + frac) * 1000  # fractional seconds to ms

    total_ms = (
        days * 86_400_000 +
        hours * 3_600_000 +
        mins * 60_000 +
        secs * 1_000 +
        ms
    )
    return round(total_ms, 3)

def clean_azure_span_id(id_str: str) -> str:
    """Strip Azure's '|traceId.' prefix from span IDs."""
    if "|" in id_str:
        return id_str.split(".")[-1]
    return id_str

def azure_to_dataframe(rows_json: str | list) -> pd.DataFrame:
    """
    Convert Azure App Insights JSON export to normalized DataFrame.
    Input: list of row dicts from the requests or dependencies table.
    """
    rows = json.loads(rows_json) if isinstance(rows_json, str) else rows_json
    normalized = []

    for row in rows:
        dims = row.get("customDimensions", {})
        # Handle both string and dict customDimensions
        if isinstance(dims, str):
            try: dims = json.loads(dims)
            except: dims = {}

        span = {
            "source":         "azure",
            "trace_id":       row.get("operation_Id"),
            "span_id":        clean_azure_span_id(row.get("id","")),
            "parent_span_id": clean_azure_span_id(row.get("operation_ParentId","")),
            "name":           row.get("name"),
            "start_time":     row.get("timestamp"),
            "duration_ms":    parse_azure_duration(row.get("duration","0:0:0")),
            "status":         "OK" if row.get("success") else "ERROR",
            "http_status":    row.get("resultCode"),
            # Span type (requests vs dependencies)
            "span_type":      row.get("itemType","unknown"),
            # Azure-specific fields
            "target":         row.get("target"),
            "dependency_type":row.get("type"),
            "operation_name": row.get("operation_Name"),
            "cloud_role":     row.get("cloud_RoleName"),
            # OTel attributes (landed in customDimensions)
            "llm_system":     dims.get("gen_ai.system"),
            "llm_model":      dims.get("gen_ai.request.model"),
            "input_tokens":   dims.get("gen_ai.usage.input_tokens"),
            "output_tokens":  dims.get("gen_ai.usage.output_tokens"),
        }
        normalized.append(span)

    return pd.DataFrame(normalized)
πŸ“Š Trace Analysis Queries (pandas)
"""Standard pandas queries for trace analysis.
df = otlp_to_dataframe(trace_json)  # from snippet 1
"""
import pandas as pd

# ── Critical Path ────────────────────────────────────────────
def critical_path(df: pd.DataFrame) -> pd.DataFrame:
    """Find the longest chain of sequential spans (the bottleneck)."""
    return df.sort_values("duration_ms", ascending=False).head(5)

# ── Token + Cost Summary ─────────────────────────────────────
def token_cost_summary(df: pd.DataFrame) -> dict:
    """Total tokens and estimated cost across all LLM spans."""
    llm_spans = df[df["llm_model"].notna()]
    return {
        "total_input_tokens":  int(llm_spans["input_tokens"].sum()),
        "total_output_tokens": int(llm_spans["output_tokens"].sum()),
        "total_tokens":        int(llm_spans["total_tokens"].sum()),
        "estimated_cost_usd":  round(llm_spans["est_cost_usd"].sum(), 6),
        "llm_calls":           len(llm_spans),
        "models_used":         llm_spans["llm_model"].unique().tolist(),
    }

# ── Error Analysis ───────────────────────────────────────────
def error_summary(df: pd.DataFrame) -> pd.DataFrame:
    """All error spans with their messages."""
    return df[df["status"] == "ERROR"][
        ["trace_id","span_id","name","duration_ms","error_msg"]
    ]

# ── Latency Percentiles per Span Name ───────────────────────
def latency_by_operation(df: pd.DataFrame) -> pd.DataFrame:
    """p50/p95/p99 latency grouped by span name."""
    return df.groupby("name")["duration_ms"].agg([
        ("count","count"),
        ("p50",  lambda x: x.quantile(0.50)),
        ("p95",  lambda x: x.quantile(0.95)),
        ("p99",  lambda x: x.quantile(0.99)),
        ("max",  "max"),
    ]).round(1).sort_values("p95", ascending=False)

# ── Parallel vs Sequential Detection ────────────────────────
def find_parallel_spans(df: pd.DataFrame) -> list:
    """Find spans that run at the same time (candidates for optimization)."""
    overlapping = []
    spans = df.sort_values("start_time").to_dict("records")
    for i, s1 in enumerate(spans):
        for s2 in spans[i+1:]:
            if s2["start_time"] > s1.get("end_time", s1["start_time"]):
                break
            if s1["parent_span_id"] == s2["parent_span_id"]:  # siblings
                overlapping.append((s1["name"], s2["name"]))
    return overlapping

# ── Anomaly Detection ────────────────────────────────────────
def detect_anomalies(df: pd.DataFrame, latency_threshold_ms: float = 3000) -> pd.DataFrame:
    """Flag spans that exceed latency threshold or have errors."""
    return df[
        (df["duration_ms"] > latency_threshold_ms) |
        (df["status"] == "ERROR") |
        (df["total_tokens"].fillna(0) > 10_000)
    ][["name","duration_ms","status","total_tokens","error_msg"]]

# ── Waterfall Data for Visualization ─────────────────────────
def trace_waterfall(df: pd.DataFrame) -> pd.DataFrame:
    """Compute relative start times for waterfall chart."""
    if df.empty: return df
    t0 = df["start_time"].min()
    df = df.copy()
    df["start_rel_ms"] = (df["start_time"] - t0).dt.total_seconds() * 1000
    df["end_rel_ms"]   = df["start_rel_ms"] + df["duration_ms"]
    df["width_pct"]    = df["duration_ms"] / df["end_rel_ms"].max() * 100
    return df.sort_values("start_rel_ms")
πŸ”§ OTel Collector Config (otel-collector.yaml)
# otel-collector.yaml
# Route traces from multiple apps to multiple backends simultaneously.
# Processes: batch, filter, attribute enrichment, PII redaction.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  # Batch spans for efficient export (reduces API calls)
  batch:
    timeout: 5s
    send_batch_size: 512

  # Add environment metadata to all spans
  resource/add_env:
    attributes:
      - key: deployment.environment
        value: production
        action: upsert

  # Redact PII from attributes before export
  attributes/redact_pii:
    actions:
      - key: http.request.header.authorization
        action: update
        value: "[REDACTED]"
      - key: db.statement
        action: hash  # SHA256 instead of delete

  # Filter out health-check spans (noise reduction)
  filter/drop_healthchecks:
    error_mode: ignore
    traces:
      span:
        - 'attributes["http.route"] == "/health"'
        - 'attributes["http.route"] == "/ping"'

  # Memory limiter (prevent OOM in high-traffic)
  memory_limiter:
    check_interval: 1s
    limit_percentage: 75
    spike_limit_percentage: 25

exporters:
  # Self-hosted Jaeger (for development)
  jaeger:
    endpoint: jaeger:14250
    tls:
      insecure: true

  # Grafana Tempo (for production)
  otlp/tempo:
    endpoint: tempo.monitoring:4317
    tls:
      insecure: false

  # AWS X-Ray (if AWS is your primary cloud)
  awsxray:
    region: us-east-1

  # Azure Monitor (if Azure)
  azuremonitor:
    connection_string: "${APPLICATIONINSIGHTS_CONNECTION_STRING}"

  # Debug logging (development only)
  logging:
    verbosity: detailed

service:
  pipelines:
    # All traces β†’ Tempo (primary store)
    traces/all:
      receivers:  [otlp]
      processors: [memory_limiter, resource/add_env, attributes/redact_pii, filter/drop_healthchecks, batch]
      exporters:  [otlp/tempo]

    # LLM traces only β†’ separate pipeline with LLM-specific processing
    traces/llm:
      receivers:  [otlp]
      processors: [memory_limiter, batch]
      exporters:  [otlp/tempo, azuremonitor]
  
  telemetry:
    logs:
      level: warn
🐍 Instrument an LLM call (Python SDK)
"""Instrument any Anthropic API call with OTel tracing.
Produces spans with GenAI semantic conventions (gen_ai.* attributes)
that work with LangSmith, Langfuse v3, Jaeger, Tempo, and X-Ray."""
import os, time
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from anthropic import Anthropic

# ── Setup TracerProvider ──────────────────────────────────────
resource = Resource.create({
    "service.name":    os.getenv("SERVICE_NAME", "my-llm-app"),
    "service.version": "1.0.0",
    "deployment.environment": os.getenv("ENV", "development"),
})
provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(
    endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"),
    insecure=True,
)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("my-llm-app", "1.0.0")

client = Anthropic()

def traced_llm_call(
    system: str,
    user_message: str,
    model: str = "claude-sonnet-4-6",
    max_tokens: int = 800,
    parent_context=None,
) -> tuple[str, dict]:
    """
    Make an Anthropic API call with full OTel instrumentation.
    Returns (response_text, telemetry_dict).
    """
    ctx = parent_context or trace.get_current_span().get_span_context()

    with tracer.start_as_current_span(
        "anthropic.messages.create",
        kind=trace.SpanKind.CLIENT,
    ) as span:
        # Set GenAI semantic convention attributes
        span.set_attribute("gen_ai.system",            "anthropic")
        span.set_attribute("gen_ai.operation.name",    "chat")
        span.set_attribute("gen_ai.request.model",     model)
        span.set_attribute("gen_ai.request.max_tokens", max_tokens)

        t0 = time.perf_counter()
        try:
            response = client.messages.create(
                model=model,
                max_tokens=max_tokens,
                system=system,
                messages=[{"role": "user", "content": user_message}],
            )
            latency_ms = (time.perf_counter() - t0) * 1000

            # Record usage metrics
            span.set_attribute("gen_ai.usage.input_tokens",  response.usage.input_tokens)
            span.set_attribute("gen_ai.usage.output_tokens", response.usage.output_tokens)
            span.set_attribute("gen_ai.response.model",      response.model)
            span.set_attribute("gen_ai.response.finish_reason", response.stop_reason)
            span.set_attribute("http.status_code",           200)

            # Cost estimate (adjust per model pricing)
            cost = (response.usage.input_tokens  / 1_000_000 * 3.00 +
                    response.usage.output_tokens / 1_000_000 * 15.00)
            span.set_attribute("gen_ai.usage.cost_usd", round(cost, 6))

            span.set_status(trace.StatusCode.OK)

            return response.content[0].text, {
                "trace_id":      format(span.get_span_context().trace_id, "032x"),
                "span_id":       format(span.get_span_context().span_id, "016x"),
                "latency_ms":    round(latency_ms, 1),
                "input_tokens":  response.usage.input_tokens,
                "output_tokens": response.usage.output_tokens,
                "cost_usd":      round(cost, 6),
            }

        except Exception as e:
            span.set_status(trace.StatusCode.ERROR, str(e))
            span.record_exception(e)
            raise
🎀 FDL Interview β€” OpenTelemetry
Customer-facing Q&A for observability value, trace storytelling, production signals, latency debug, and multi-cloud normalization.
"Why does observability matter for our FDL engagement?"
Customerβ–Ύ
AI systems fail in non-obvious ways β€” wrong retrieval, slow tool calls, token spikes. Observability turns "the assistant felt slow/wrong" into actionable spans: which step failed, how long it took, and what data flowed through. Without traces, you're debugging blind after every pilot complaint.
For FDL: observability is how you prove value to sponsors (latency SLAs met), earn IT trust (standard OTLP, not proprietary black boxes), and shorten incident MTTR. It's the bridge between demo and production β€” sponsors fund what they can measure.
Customer scenario: VP asks if the copilot is "working." You show a dashboard: 94% requests under 3s, retrieval p95 400ms, 2% error rate traced to timeout on legacy API β€” concrete, not anecdotal.
The trap: Treating observability as a post-pilot nice-to-have. Instrument from day one or you can't defend the architecture under scrutiny.
"How do you explain traces to a non-technical sponsor?"
Customerβ–Ύ
A trace is a receipt for one user request β€” a timeline showing every step (search docs, call API, generate answer) with how long each took. Like tracking a package: you see where it stalled, not just "delayed."
Sponsor-friendly framing: "When something goes wrong, we don't guess β€” we open the receipt and see exactly which step failed." Show one waterfall view, highlight the slow red bar, explain the fix in business terms ("database lookup took 8 seconds β€” we're adding a cache").
Customer scenario: Sponsor says answers feel slow. You show a trace: 80% of time is in embedding search, not the LLM. Fix is index tuning β€” sponsor understands the investment.
The trap: Showing raw JSON spans. Use visual timelines and one-sentence annotations per span.
"What signals tell us we're production-ready?"
Scopeβ–Ύ
Production-ready means SLOs on latency (p50/p95), error rate, and saturation β€” plus AI-specific signals: retrieval hit rate, tool failure rate, tokens per request, and hallucination flags. If you can't alert on these, you're not ready to scale users.
Minimum bar: distributed tracing on every request (trace_id propagated), RED metrics (rate, errors, duration) per service span, log correlation via trace_id, and dashboards for the AI pipeline stages. Add custom spans for embed, retrieve, llm_call, tool_invoke so bottlenecks are visible.
Customer scenario: Go-live checklist: p95 end-to-end < 5s, tool errors < 1%, 100% traces sampled in staging / 10% in prod, pager fires on error rate > 2% for 5 min.
The trap: "We have logs." Logs without trace correlation can't reconstruct a single user's journey across microservices.
"Users report latency β€” how do you debug with traces?"
Technicalβ–Ύ
Pull a slow trace, sort spans by duration, find the critical path. Common culprits: cold-start embedding, N+1 tool calls, oversized context serialization, or missing connection pooling. Fix the longest span first β€” that's your latency budget leak.
Debug workflow: filter traces by duration > SLA β†’ compare fast vs slow traces β†’ diff span breakdown. Lab 1 Parse JSON Trace and Lab 4 AI Trace Analyst teach span parsing and automated bottleneck detection. Look for parallelizable sequential calls and duplicate retrievals.
Customer scenario: p95 latency 12s. Trace shows 3 sequential LLM calls that could be one; collapsing the graph cuts latency to 4s.
The trap: Blaming the LLM provider globally. Span-level breakdown almost always reveals a fixable pipeline issue.
"We have AWS X-Ray and Azure Monitor β€” can you normalize both?"
Technicalβ–Ύ
Yes β€” OTel is the lingua franca. Ingest vendor-specific formats (X-Ray segments, Azure Application Insights), map to OTLP span model (trace_id, span_id, parent_id, attributes, status), and query uniformly. Lab 3 Normalize + Diff demonstrates cross-vendor comparison.
Normalization challenges: different attribute naming (http.url vs http.target), clock skew across regions, and sampling differences. Build a mapping layer once, validate with golden traces from each cloud, and store canonical OTLP in your observability backend (Grafana Tempo, Datadog, etc.).
Customer scenario: Multi-cloud AI pipeline: Lambda on AWS, Azure OpenAI. Traces from both land in one Tempo instance via OTLP exporters β€” single pane for RCA.
The trap: "We'll standardize on one cloud's format." Hybrid enterprises need normalization, not vendor lock-in on trace schema.
"We had an incident β€” how do traces support RCA?"
Scopeβ–Ύ
Post-incident RCA with traces: identify affected trace_ids (from logs/alerts), reconstruct the request path, pinpoint the first failing span, determine blast radius (how many traces share that failure mode), and add a regression alert. Traces answer when, where, and what β€” not always why, but they narrow it fast.
RCA template: (1) timeline of detection β†’ mitigation, (2) exemplar trace with annotated failure span, (3) root cause category (config, dependency, code, capacity), (4) corrective actions with owners, (5) new monitor on the failure signature. Preserve traces with error status for 30+ days for pattern analysis.
Customer scenario: Copilot returned empty answers for 2 hours. Traces show retrieval span returning 0 results after a bad index deploy β€” correlate deploy timestamp, rollback, add pre-deploy retrieval smoke test.
The trap: RCA that ends at "model hallucinated." Push to the span that fed bad context or the tool that returned empty data.