Skip to content

6. Signal translation and instrumentation

The production implementation in otel.py translates approved platform envelopes into OpenTelemetry SDK calls. Optional SDK imports are confined to that module.

The dependency-free performance execution adapter contracts do not translate candidates, contexts, or adapter lifecycle events into telemetry. Consumers may explicitly instrument their own approved Operations or Observations around an adapter, subject to the schema and safety floor; the platform does not auto-discover ML frameworks or import their packages from the base evaluation surface. The same rule applies to ephemeral paired candidate observations: they are never translated into telemetry or persisted as report fields. Opt-in execution-identity collection likewise emits no telemetry and does not auto-import or probe an accelerator framework; its bounded local result remains separate from Collector and resource identity. The implemented EvaluationTelemetryAdapter and GenAiAggregateTelemetryAdapter are separate, explicit aggregate bridges: they use a Consumer-supplied Telemetry implementation and preflight Consumer schemas. They can emit approved aggregate Operations/Observations; ordinary evaluator calls do not automatically invoke them. Disabled bridges add no telemetry side effects, but still execute any Consumer evaluation explicitly requested through their evaluation seam.

Resource mapping

Enabled startup constructs one OpenTelemetry Resource directly from seven platform fields and registered custom ResourceIdentity.attributes. SDK environment, cloud, host and plugin resource detectors do not run or inject unvalidated attributes, including with an explicitly empty environment mapping. Consumers must declare and validate any desired enrichment.

OpenTelemetry resource key Source
service.name ResourceIdentity.service_name
service.namespace TelemetryConfig.resource.service_namespace
service.version ResourceIdentity.service_version
service.instance.id Final identity instance ID after optional environment override
deployment.environment.name ResourceIdentity.deployment_environment
telemetry.schema.version TelemetrySchema.version
telemetry.config.fingerprint TelemetryConfig.fingerprint

Because custom attributes are applied last, the current implementation permits a registered custom resource attribute with the same key to replace one of these generated values. The schema's reserved capacity does not prohibit such names. Supported consumers are expected to keep generated identity keys platform-owned.

Traces and operations

When traces are enabled, startup creates a TracerProvider with shutdown_on_exit=False, configured SpanLimits, one BatchSpanProcessor, and one OTLP span exporter. The tracer uses the schema instrumentation scope and schema version.

An operation maps as follows:

Platform field or event OpenTelemetry representation
OperationSpec.name Span name
SERVER / INTERNAL / CLIENT Matching SpanKind
Bound context Initial span attributes
Operation attributes Overlay bound context by key
Normal successful exit Status OK; operation.outcome attribute
Registered error outcome Status ERROR; operation.outcome attribute
Failure category failure.category attribute when present
Exceptional exit Outcome forced to failure, status ERROR, exception class in exception.type

Spans use record_exception=False and set_status_on_exception=False. The adapter implements the exact status and exception-type behavior itself and never records exception messages or stack traces. A conversion failure disables that one operation or step and emits a local diagnostic; it does not suppress an exception raised by the business block.

Metrics

When metrics are enabled, startup creates a PeriodicExportingMetricReader and MeterProvider with shutdown_on_exit=False. Export interval and timeout come from batching configuration. The meter uses the schema instrumentation scope and version.

Metric instruments are created lazily on the first observation and cached by metric name behind a lock:

InstrumentKind SDK factory Observation call
COUNTER create_counter add(value, attributes)
UP_DOWN_COUNTER create_up_down_counter add(value, attributes)
HISTOGRAM create_histogram record(value, attributes)

The factory receives the registered name, unit, and description. Only observation attributes are metric dimensions; bound TelemetryContext is not added. SDK or instrument errors are caught at the observation boundary and reported as metric_conversion.

All owned Consumer and FastAPI metric producers pass through one runtime series-admission budget before SDK accumulation. Per-instrument admission is atomic and only new series reserve shared total capacity; admitted series avoid that total-budget lock. Exhaustion drops unseen combinations with a fixed bounded metric_cardinality diagnostic, without retaining rejected values or evicting admitted entries.

Integer MetricObservation values must fit signed 64-bit OTLP integers. Cumulative integer aggregates can exceed that range despite valid inputs; export normalization promotes such values to finite doubles, with possible precision loss beyond the double's exact integer range. Nonfinite or unrepresentable points are omitted without preventing healthy peers from exporting. The same stateless normalization serves both transports, preserves valid metadata/exemplars and does not mutate SDK-owned snapshots or retain a second per-series accumulation map.

The translator is created even when traces or metrics are disabled. It receives a no-op tracer or meter for the disabled signal, so schema validation still runs but valid observations produce no exported data. SQLAlchemy instrumentation additionally requires a real trace provider and therefore skips disabled tracing.

Events and application logs

When logs are enabled, startup creates a LoggerProvider, one BatchLogRecordProcessor, one OTLP log exporter, and one _OtelLogHandler attached to the root Python logger. Records from opentelemetry and grpc logger hierarchies are filtered to avoid feedback.

EventObservation writes to the standard logger named <instrumentation_scope>.telemetry, using the event severity, the event name as the Python message, and event.name plus event attributes as record extras. Standard Python logger thresholds still apply; for example, the default root INFO level suppresses a DEBUG event before it reaches handlers.

The OTLP handler deliberately does not export arbitrary formatted messages:

Log field Mapping
Body Registered record.event.name, otherwise literal application.log; truncated to configured body length
Event name Registered event name or None
Timestamp record.created converted to nanoseconds
Observed timestamp Current time_ns()
Severity Python level mapped to DEBUG/INFO/WARN/ERROR/FATAL number and original levelname text
Context Current platform context attributes
Record extras Only names registered as context or event attributes and only supported scalar/string-list values
Exception Exception class name in exception.type; no message or traceback body

Copied string extras are redacted for credential assignments (authorization, idempotency key, password, secret, token) and common database connection URLs, then truncated to 256 characters. Copied lists/tuples contain at most five redacted strings and become tuples. Normalized extras pass the canonical core value validator: non-finite floats and integers outside signed 64-bit range are omitted with a bounded log_conversion diagnostic; healthy fields and records remain available. Context attributes were already validated by the core and are copied without the handler's 256-character redaction step. The final attribute dictionary is sorted by key and sliced to log_attribute_count; this means fields after the limit, including generated fields, can be dropped by ordering.

The handler uses a ContextVar recursion guard. Any conversion error drops the record and emits one log_conversion diagnostic.

When the OTLP log signal is disabled, no OTLP handler/provider is installed. EventObservation still uses the standard Python logger, so a runtime-owned or pre-existing console handler can receive its sanitized registered event according to normal logger levels.

Console logging

Logging configuration runs regardless of whether OTLP logs are enabled. When console output is enabled, the runtime adds one root stream handler:

  • text: <LEVEL> <logger-name> <registered-event-name-or-application.log>;
  • JSON: compact, key-sorted severity, logger, and bounded message fields.

Neither formatter includes the original Python log message, exception text, or arbitrary extras. The handler uses the registered event name only when record.event.name exactly belongs to the schema.

FastAPI instrumentation

instrument_fastapi(app) is effective only while open and when enabled in configuration. Identity comparison prevents the same app object from being instrumented twice by one runtime. It supplies the runtime's tracer and meter providers, substituting explicit no-op providers for disabled signals. It passes the configured excluded routes as a comma-separated string, disables request and response header capture, and excludes ASGI receive and send spans.

Before trace export, the runtime removes raw HTTP targets and URLs (including path and query values), captured request/response header attributes, exception messages, stack traces, and status descriptions. Route templates, methods, status codes, span relationships, and exception types remain available for operations. This export boundary also protects spans created by framework code that records exception details independently of the platform operation adapter.

If instrumentation partly fails, the runtime attempts to uninstrument that app and reports a diagnostic. Successfully instrumented apps are uninstrumented during shutdown. Pending and committed app ownership is exclusive across platform runtimes. A competing hook call returns without entering the instrumentor or acquiring cleanup rights. An app already marked instrumented outside this protocol is left alone. Ownership is released after cleanup; pending registration that loses to shutdown removes its hooks before releasing ownership. The reservation uses weak runtime references and does not keep an abandoned runtime alive. External instrumentors must coordinate their own concurrent mutations; the platform cannot serialize arbitrary outside code.

SQLAlchemy instrumentation

instrument_engine(engine) requires an open runtime, enabled SQLAlchemy instrumentation, and an enabled trace provider. An engine object is registered once by object ID. The runtime attaches three SQLAlchemy event listeners:

sequenceDiagram
    participant DB as SQLAlchemy engine
    participant RT as Telemetry runtime
    participant SP as database.query span
    DB->>RT: before_cursor_execute
    RT->>SP: start CLIENT span with db.system.name
    alt success
      DB->>RT: after_cursor_execute
      RT->>SP: status OK and end
    else failure
      DB->>RT: handle_error
      RT->>SP: exception.type, status ERROR, and end
    end

Active spans are keyed by execution-context object ID behind a lock. The emitted span contains the fixed name database.query, kind CLIENT, the engine dialect name in db.system.name, status, and exception class when applicable. SQL text, parameters, comments, connection URLs, and exception messages are not captured. Listeners are removed during shutdown. The same target reservation prevents competing platform runtimes from registering listeners on one engine. Completed registration commits against closure; a late registration removes its newly added listeners in reverse order. Neither SQL text nor exception messages enter ownership diagnostics.

OTLP exporter construction

Each enabled signal gets its own exporter instance and the same resolved header mapping and export timeout.

For gRPC, the configured common endpoint is passed unchanged. In secure mode the runtime creates channel credentials from optional root CA bytes and an optional client key/certificate pair. For HTTP/protobuf, the runtime appends /v1/traces, /v1/metrics, or /v1/logs to the common base path and passes CA, client-key path, client-certificate path, headers, and timeout to the signal exporter. The HTTP session enforces explicit headers and TLS policy for all three signals, disables ambient Requests authentication/proxy/CA inheritance and uses explicit no-compression policy. Empty configured authentication does not trigger SDK environment fallback. Each exporter owns and closes its session; concurrent runtimes do not exchange credentials or modify global environment state.

Applications always target one Collector endpoint. Vendor endpoints and vendor credentials are only present in Collector backend configuration.