```python:inference/core/telemetry.py
# ---------------------------------------------------------------------------
# Graceful opentelemetry imports — everything below is noop when not installed
# ---------------------------------------------------------------------------
from typing import Any, Dict, Optional

from opentelemetry import trace

try:

    _OTEL_AVAILABLE = True
except ImportError:
    _OTEL_AVAILABLE = False

_tracer = None


def _get_tracer():
    global _tracer
    if _tracer is None and _OTEL_AVAILABLE:
        _tracer = trace.get_tracer("inference")
    return _tracer


# ---------------------------------------------------------------------------
# Public helpers — always safe to call
# ---------------------------------------------------------------------------


class _NoopSpanCM:
    """A tiny no-op context manager that yields None.

    Implemented as a class to avoid the overhead of the generator-based
    contextmanager wrapper in hot paths.
    """

    __slots__ = ()

    def __enter__(self):
        return None

    def __exit__(self, exc_type, exc, tb):
        # Do not suppress exceptions
        return False


def start_span(name: str, attributes: Optional[Dict[str, Any]] = None):
    """Start a new span as a child of the current context.

    Yields the span (or None when OTel is not available).
    """
    if not _OTEL_AVAILABLE:
        return _NoopSpanCM()
    tracer = _get_tracer()
    # tracer.start_as_current_span(...) already returns a context manager
    return tracer.start_as_current_span(name, attributes=attributes)




def set_span_attribute(key: str, value: Any) -> None:
    """Set an attribute on the current active span.

    Noop when OTel is unavailable or there is no recording span.
    Callers never need to check for None spans.
    """
    if not _OTEL_AVAILABLE:
        return
    span = trace.get_current_span()
    if span and span.is_recording():
        span.set_attribute(key, value)
```