Skip to content

credencestack.otel

OpenTelemetry traces for runs (the [otel] extra). Off by default. Builds spans from the trace-event pipeline, so every connector gets the same telemetry without code of its own. User documentation: Observability; design: OpenTelemetry architecture and decision 0003.

Responsibilities

  • Resolve the settings: CLI flags over the standard OTEL_* variables, off unless --otel or CREDENCESTACK_OTEL_ENABLED=1 (config.py).
  • Hold every span, event and attribute name in one place (semconv.py).
  • Build the span tree from trace events: run, scenario, invoke_agent, execute_tool, chat, grade; findings, faults, control signals and approvals as events (spans.py).
  • Own the tracer provider and exporter, never let export slow or fail a run, and explain export errors in one line (tracer.py).
  • Redact and cap captured content; never capture confidential scenarios (redaction.py).
  • Propagate W3C Trace Context to HTTP and MCP agents (propagation_headers, propagation_env).
  • Check a span tree and normalise it for golden files (validate.py); capture spans in memory (testing.py).

Non-goals

  • Metrics and logs (see the roadmap).
  • Instrumenting frameworks: their own spans nest under invoke_agent when they use the global tracer provider.

Public API

Name Kind Signature Purpose Errors Effects
INSTALL_HINT constant INSTALL_HINT = "pip install 'credencestack[otel]'" The pip command printed when telemetry is on but the [otel] extra is missing. - -
TelemetryConfig model TelemetryConfig(enabled, exporter, endpoint, protocol, headers, file, capture_content, granularity, …) Resolved telemetry settings for one command. - data
TelemetryConfigError exception class TelemetryConfigError A telemetry setting is invalid (the message says which and why). - -
TelemetryNotInstalled exception class TelemetryNotInstalled Telemetry was enabled but the [otel] extra is not installed. - -
active function active() -> Telemetry \| None The telemetry of the current command, or None when it is off. - reads the process's and this context's active telemetry
available function available() -> bool True if the OpenTelemetry SDK can be imported (without importing it). - looks for the OpenTelemetry SDK without importing it
otlp_hint function otlp_hint(config: TelemetryConfig, environ: Mapping[str, str] \| None = None) -> str \| None A one-line hint when OTLP variables are set but telemetry is off, else None. - reads the environment
propagation_env function propagation_env() -> dict[str, str] TRACEPARENT/TRACESTATE for a launched agent process ({} when off). - pure (reads the active OpenTelemetry context)
propagation_headers function propagation_headers() -> dict[str, str] traceparent/tracestate headers for an outgoing agent request ({} when off). - pure (reads the active OpenTelemetry context)
resolve function resolve(settings: OtelSettings \| None = None, *, environ: Mapping[str, str] \| None = None, max_content_bytes: int \| None = None) -> TelemetryConfig The telemetry configuration of one command, from its resolved [otel] settings. TelemetryConfigError: if a value is invalid. reads the environment
start function start(config: TelemetryConfig, *, run_id: str \| None = None, out: IO[str] \| None = None, simple: bool = False, exporter: Any = None, install_global: bool = True, on_failure: Callable[[str], None] \| None = None) -> Telemetry Start telemetry for this process (the CLI calls it once per command). TelemetryNotInstalled: if the [otel] extra is missing. imports OpenTelemetry; creates a tracer provider and exporter; may install the global tracer provider
stop function stop(tel: Telemetry \| None = None) -> str \| None Shut down tel (default: the active one); return its summary line. - flushes and shuts down the exporter (bounded); may send spans over the network
suspended function suspended() -> Generator[None] No telemetry in this context, even if a command-wide one is active. - sets a context variable for the duration
use function use(tel: Telemetry) -> Generator[Telemetry] Make tel the active telemetry in this context (tests, the conformance check). - sets a context variable for the duration

Examples

Settings, and one episode's spans in memory

examples/dev/telemetry.py
"""Module reference example: resolve the telemetry settings and capture one episode's spans."""

from __future__ import annotations

from credencestack import otel
from credencestack.agents import scripted_naive
from credencestack.connectors.python import PythonConnector
from credencestack.otel.testing import capture
from credencestack.packs import load_packs
from credencestack.runner.episode import run_episode
from credencestack.settings import OtelSettings

# Settings: off unless enabled; OTLP variables alone only give a hint.
env = {"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"}
config = otel.resolve(OtelSettings(), environ=env)
print("enabled:", config.enabled)
print("hint:", otel.otlp_hint(config, env))
print(otel.resolve(OtelSettings(enabled=True, protocol="grpc", granularity="run"), environ={}))

# One episode, spans captured in memory (no exporter, no network).
scenario = next(s for p in load_packs(["payments"]) for s in p.scenarios if s.id == "PAY-001")
with capture() as (memory, tel):
    run = tel.start_run(
        run_id="example",
        connector="python",
        agent="scripted_naive",
        packs=["payments"],
        epochs=1,
        seed=0,
    )
    run_episode(scenario, PythonConnector(scripted_naive))
    run.finish()
for span in sorted(memory.get_finished_spans(), key=lambda s: s.start_time or 0):
    parent = "root" if span.parent is None else "child"
    print(f"{span.name:<45} {span.kind.name:<8} {parent}")
enabled: False
hint: OTel: OTEL_EXPORTER_OTLP_* is set but telemetry is off; add --otel (or set CREDENCESTACK_OTEL_ENABLED=1) to export traces.
TelemetryConfig(enabled=True, exporter='otlp', endpoint=None, protocol='grpc', headers=None, file=None, capture_content=False, granularity='run', trace_url_template=None, agent_spans='nest', max_content_bytes=8192, service_name=None, metrics=False, sample_rate=1.0, warnings=())
credencestack run example                     INTERNAL root
credencestack scenario PAY-001 #0             INTERNAL root
invoke_agent scripted_naive                   INTERNAL child
execute_tool lookup_invoice                   INTERNAL child
execute_tool lookup_vendor                    INTERNAL child
execute_tool pay_invoice                      INTERNAL child

Invariants and gotchas

  • credencestack.otel (its __init__, config, semconv, redaction) imports nothing from OpenTelemetry. spans, tracer, hub, validate and testing are loaded only when telemetry is on.
  • The OpenTelemetry API itself is installed with the core (inspect-ai depends on fastapi, which depends on it); the SDK and exporters come only with [otel].
  • Environment.listeners must not raise: EpisodeSpans.on_event swallows its own errors and counts them in RunSpans.dropped.
  • Scenario spans stay open until the run is graded and end with the episode's own end time; the grade span is zero-length.
  • Trace ids never enter the hash-chained trace events; they go to otel/ids.json.
  • The global tracer provider can be set once per process: tests that need it run a subprocess.

Where the tests are

  • tests/unit/test_api.py
  • tests/unit/test_otel.py
  • tests/unit/test_otel_workflows.py
  • tests/unit/test_settings.py