5. Runtime lifecycle¶
execute_llm_judges() owns every child until its result or exception is observed. Caller cancellation
or an unexpected child interruption cancels and joins all remaining cooperative judge tasks before
the original exception propagates. No new requests or retries are admitted during cleanup, and owned
task retention remains bounded by declared concurrency. Ordinary provider failures retain the existing
safe error/retry evidence; cancellation does not fabricate a completed execution or usage totals.
Consumer judge coroutines must cooperate with cancellation; this does not terminate remote provider
work or guarantee forced termination of a cancellation-resistant coroutine.
Spawned evaluation uses a dedicated socket pair with bounded length-prefixed
JSON frames. The parent checks its monotonic receive deadline between reads of
at most 64 KiB, including partial headers and bodies. Announced body length is
checked against the Safety Floor and configured report limit before allocation.
Timeout/EOF returns the existing closed child-failure outcome; lower-limit excess
returns report_oversized. Local deadline contracts allow 200 ms scheduling grace.
Direct-child cleanup then has separate join/terminate/kill waits of 0.1/1/1 seconds.
No reader helper thread is created. Local evidence covers macOS; socket transport
avoids dependence on Windows native multiprocessing pipe handles.
TelemetryRuntime is the public lifecycle facade. It owns a concrete adapter and exposes telemetry,
framework instrumentation, controlled thread propagation, flushing, and shutdown.
Performance execution adapters are independent Consumer-supplied objects, not TelemetryRuntime
adapters. Their opt-in setup/invoke/teardown lifecycle is owned explicitly by
telemetry.performance.execute_sync() or execute_async(); no runtime startup, shutdown, framework
hook, global registry, or adapter discovery is involved.
Both execution functions run teardown exactly once only after successful setup.
An ordinary teardown failure preserves a pending invocation exception, cancellation,
or interrupt, adding only the fixed candidate teardown failed note. A teardown-only
failure propagates to the direct caller; evaluation evidence retains only the safe
exception class, never its message. Async cleanup remains awaited and cooperative.
PerformanceEvaluator.evaluate_adapter() derives and passes candidate seeds only through the explicit
adapter context; it never changes a process-global random generator.
Paired evaluation is likewise an in-process Consumer evaluation seam: it creates no runtime lifecycle,
framework hook, adapter discovery, or telemetry side effect.
collect_execution_identity() is also an explicit in-process helper: it does not run during runtime
construction, startup, flush, shutdown, disabled telemetry, or framework instrumentation. Optional
framework readers are Consumer-supplied and invoked only by that explicit call.
Construction¶
Open-loop serving drains admitted work until its configured drain deadline, then cancels and awaits remaining owned workers. Exceptional production and caller cancellation use that same cleanup; no stop markers are put into a queue after its readers exit. Cooperative cleanup is verified with a 200 ms local test grace, not a forced-termination guarantee for cancellation-resistant Consumer clients. Closed-loop serving also cancels and joins all owned cooperative workers on every exit, including a client's self-cancellation and caller cancellation. Evaluator-owned drain expiry retains timeout accounting; external interruption propagates after cleanup, with primary failures preserved.
flowchart TD
A[TelemetryRuntime.create] --> B{config.enabled?}
B -->|no| N[Create _NoopRuntime]
B -->|yes| C[Validate custom resource attributes]
C --> D[Copy supplied environment or os.environ]
D --> E{instance_id_env configured?}
E -->|yes| F[Read value and replace identity instance ID]
E -->|no| G[Keep supplied instance ID]
F --> H[Require identity and config environments to match]
G --> H
H --> I{adapter_factory supplied?}
I -->|yes| J[Construct supplied adapter]
I -->|no| K[Lazy import telemetry.otel]
K --> L[Construct OpenTelemetryRuntime]
J --> M[Create public facade]
L --> M
Disabled construction returns before resource-schema validation, environment lookup, environment
matching, adapter import, logging changes, or provider creation. Its telemetry is NOOP_TELEMETRY,
force_flush() returns True, and every other runtime action does nothing.
Enabled construction validates resource attributes, applies the optional instance-ID override, and
requires exact deployment-environment equality. A supplied adapter_factory is a test seam. Otherwise
the runtime imports telemetry.otel only at this point. Missing opentelemetry*, grpc, or sqlalchemy
modules are translated to a RuntimeError saying the optional dependency is not installed. Other import
failures propagate unchanged.
Enabled adapter startup¶
The production adapter resolves secret headers, creates the OpenTelemetry Resource, initializes only
the enabled signal providers, creates its OpenTelemetry translator, attaches an OTLP log handler when
logs are enabled, then configures process logging.
Resource construction uses only validated explicit identity fields, without ambient SDK detectors.
Owned HTTP exporters likewise enforce explicit transport policy without reading ambient credentials
or temporarily mutating process environment. Metric providers share bounded lifetime series admission
between Consumer and framework instrumentation.
Startup validation and provider-construction errors are fatal. If startup fails after acquiring any
resources, the constructor marks itself closed, removes owned hooks and handlers, restores saved logger
levels, and attempts provider shutdown on a daemon lifecycle worker within shutdown_timeout_ms. It then
re-raises the original startup exception.
Public lifecycle state¶
stateDiagram-v2
[*] --> Open: create
Open --> Open: telemetry / instrument / force_flush
Open --> Closed: shutdown
Closed --> Closed: shutdown
Closed --> Closed: instrument (ignored)
Closed --> Closed: force_flush = true
The facade makes shutdown idempotent. It marks itself closed before calling the adapter, so a failing
adapter shutdown is not retried. Calls to instrument_fastapi() and instrument_engine() after closure
are ignored; force_flush() after closure reports success.
Flush algorithm¶
The production adapter computes one monotonic deadline from shutdown_timeout_ms. It first waits for any
existing lifecycle worker. It then starts one daemon thread named telemetry-lifecycle to flush providers
in this order:
- tracer provider;
- meter provider; and
- logger provider.
Before each provider, it passes the remaining whole milliseconds to force_flush(). A zero remaining
budget, a provider exception, a provider returning false, a worker exception, or the shared deadline
expiring makes the result false. Providers that were not created are skipped.
Only one live lifecycle worker is allowed. If a prior timed-out worker is still alive, another flush or shutdown worker is not started. The caller returns at the deadline while the existing daemon may remain blocked in third-party provider code. Shutdown retains one pending cleanup callback on that worker. When the prior flush returns, the same worker runs cleanup even if the caller's deadline has expired. The worker atomically drains pending work or relinquishes ownership; concurrent shutdown callers observe closure and do not enqueue duplicate cleanup.
Shutdown algorithm¶
The production adapter serializes the closed-state transition with a lock, computes one deadline, then:
- removes and closes its OTLP log handler and console handler;
- un-instruments FastAPI apps in reverse registration order;
- removes SQLAlchemy listeners in reverse registration order;
- clears hook ownership sets and lists;
- restores the saved logger levels;
- queues cleanup on an existing lifecycle worker, or starts one when idle; and
- on that lifecycle worker, flushes within the remaining deadline and calls
shutdown()on logger, meter, then tracer providers.
Provider shutdown calls themselves do not accept the remaining timeout. The daemon worker is the hard wall-clock boundary presented to the caller. If waiting or the worker exceeds the deadline, shutdown returns after a local timeout diagnostic. The deadline bounds the caller's wait, not provider cleanup completion. A blocked provider must eventually return for its worker to continue cleanup; no extra worker is spawned to bypass it. Framework registration reserves each target before invoking third-party code, and commits hooks under the same lock as the adapter's closed-state transition. A registration still in progress when shutdown wins reverses its hooks on return. Shutdown does not wait on that blocked registration or hold a lock across its framework calls. This is cooperative eventual hook cleanup, not forced interruption of framework code. Deterministic tests use two-second barrier/join bounds for independently owned test threads and verify shutdown completes before releasing the registration barrier.
Failure semantics after startup¶
Runtime and conversion failures after successful construction are fail-open for application behavior:
| Boundary | Failure result |
|---|---|
| FastAPI or engine instrumentation | Hook call returns; business object remains usable |
| Context/operation/metric/event conversion | Observation may be dropped; caller continues |
| Invalid production operation outcome | Existing outcome remains; caller continues |
| Operation enter/exit SDK failure | Business block and original exception are preserved |
force_flush() facade failure |
Returns False |
shutdown() facade failure |
Returns without raising |
The strict RecordingTelemetry test adapter is different: schema violations raise immediately so
consumer contract tests expose invalid vocabulary or values.
Local diagnostics¶
Failures use os.write(2, b"telemetry failure: <category>\n"), bypassing Python logging and therefore
avoiding recursive OTLP log export. Exception text, telemetry names, values, record bodies, endpoints,
and credentials are omitted. Each of runtime.py and otel.py maintains its own locked set and emits at
most one line per category within that module for the process lifetime.
Categories cover context and operation entry/exit, metric/event/log conversion, framework and engine instrumentation/callbacks, flush, cleanup, provider shutdown, lifecycle worker failure, lifecycle timeout, metric-series admission/encoding, and facade shutdown. Diagnostic writes are themselves suppressed if stderr is unavailable.
Controlled thread context¶
wrap_thread_target(callback) returns the original callback when thread propagation is disabled. When
enabled, it calls contextvars.copy_context() at wrapper creation and returns a zero-argument function
that executes the callback through that captured context. It does not create or start a thread, accept
callback arguments, or instrument arbitrary thread pools.
OpenTelemetry's active span context and the platform TelemetryContext both travel through the copied
Python context variables when callers use this wrapper.