Skip to content

OtelTracer.currentOtelSpan doesn't work with OTLP module #5889

@schickling

Description

@schickling

Summary

OtelTracer.currentOtelSpan always fails with NoSuchElementException when using the lightweight OTLP module (OtlpTracer.layer), even though Effect.currentSpan works correctly.

Current Behavior

When using the OTLP module:

  • Effect.currentSpan ✅ returns the current span
  • OtelTracer.currentOtelSpan ❌ always returns NoSuchElementException

Root Cause

The currentOtelSpan implementation checks for a special symbol marker:

// packages/opentelemetry/src/internal/tracer.ts:241-249
export const currentOtelSpan = Effect.flatMap(
  Effect.currentSpan,
  (span) => {
    if (OtelSpanTypeId in span) {
      return Effect.succeed((span as OtelSpan).span)
    }
    return Effect.fail(new Cause.NoSuchElementException())
  }
)
  • Official OpenTelemetry approach (NodeSdk, Tracer.layer): Creates OtelSpan class instances with the OtelSpanTypeId symbol → works
  • OTLP module (OtlpTracer.layer): Creates plain objects via Object.create(SpanProto) without the symbol → always fails

Workaround

// Use Effect.currentSpan instead and manually construct the span context
export const getTracingBackendUrlEffect = (span: Tracer.Span) => {
  const otelSpan = {
    spanContext: () => ({
      traceId: span.traceId,
      spanId: span.spanId,
      traceFlags: 0,
    }),
  }
  return getTracingBackendUrl(otelSpan)
}

Suggested Fix

At minimum, the JSDoc for currentOtelSpan should document this limitation:

/**
 * Get the current OpenTelemetry span.
 * 
 * **Note:** This only works when using the official OpenTelemetry API 
 * (via `Tracer.layer`, `NodeSdk.layer`, etc.). 
 * It does NOT work with the lightweight OTLP module (`OtlpTracer.layer`).
 * When using OTLP, use `Effect.currentSpan` instead.
 */

A more complete fix could provide an alternative API that works with both approaches, returning a unified interface with traceId, spanId, etc.


🤖 Generated with Claude Code

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions