Implementation guide¶
This guide explains how the current implementation works as a collaborating system. It is an educational code tour, not a second specification. For exact fields, limits, and supported compositions, follow the implementation specification. When this guide and the executable artifacts disagree, Python source, Collector YAML, tests, and scripts remain authoritative in that order.
The design in one sentence¶
The package accepts Consumer-owned meaning through a small, backend-neutral port, validates it against an immutable allowlist, translates it at the OpenTelemetry boundary, and sends it through a Collector pipeline that applies a second safety floor before isolated backend delivery.
The dependency-free evaluation core follows the same ownership rule: it executes Consumer algorithms
locally and returns payload-free evidence without automatically emitting telemetry or loading
OpenTelemetry. Explicit aggregate telemetry bridges accept Consumer-supplied Telemetry and approved
schemas; optional framework/resource/provider integrations load selected extras only when requested.
Implementation map¶
| Layer | Main implementation | Responsibility | May depend on |
|---|---|---|---|
| Public domain model | core.py |
Envelopes, schema, protocols, validation, recording and no-op adapters | Python standard library |
| Configuration | config.py |
Immutable typed configuration, secrets, endpoint rules, limits, fingerprint | Python standard library |
| Lifecycle facade | runtime.py |
Disabled/enabled selection, lazy adapter loading, hook calls, context transfer, close semantics | Core and configuration |
| OpenTelemetry adapter | otel.py |
SDK providers, signal translation, OTLP exporters, framework hooks, bounded lifecycle | Optional adapter dependencies plus inward layers |
| Evaluation core | performance/ |
Bounded algorithm trials, Measurements, statistics, reports, comparison, assessment | Python standard library |
| Explicit evaluation integrations | performance/integrations/ |
Consumer-injected telemetry and optional framework/provider adapters | Backend-neutral telemetry types and explicitly selected extras |
| Delivery pipeline | collector/ |
Intake, safety processing, sampling, batching, routing, queues, backend export | Collector components |
| Executable evidence | tests/, scripts/ |
Contract, failure, packaging, topology, and local delivery verification | Public surfaces and artifacts under test |
This dependency direction is deliberate. core.py does not know that OpenTelemetry exists, and
runtime.py imports telemetry.otel only when enabled configuration crosses the production boundary.
The base wheel therefore has no required third-party dependency and disabled telemetry cannot start an
exporter thread or mutate process logging.
This describes the platform-owned disabled construction path. It does not undo earlier explicit SDK
imports or suppress side effects in Consumer algorithms, injected readers or third-party packages.
flowchart LR
D[Consumer domain code] --> CA[Consumer adapter]
CA --> P[Telemetry protocol]
P --> V[Schema validation]
V --> R[Runtime-selected adapter]
R -->|disabled| N[No-op]
R -->|tests| REC[Recording adapter]
R -->|enabled| O[OpenTelemetry adapter]
O --> C[Collector common pipeline]
C --> B1[Backend pipeline A]
C --> B2[Backend pipeline B]
The Consumer adapter in this diagram belongs in the Consumer repository. It keeps domain enums and objects out of the generic platform while still giving the Consumer a typed interface.
Walking one telemetry operation through the code¶
1. The Consumer defines the accepted language¶
TelemetrySchema is a closed allowlist, not just descriptive metadata. Its frozen fields register
operation names, events, metrics, outcome values, failure categories, and the attribute names accepted
in each channel. Each MetricSpec also declares the instrument, unit, description, and permitted
dimensions for that metric.
Construction validates the complete vocabulary before any runtime resource is acquired. This catches duplicate metrics, mutable schema collections, excessive vocabularies, forbidden attribute-name families, and inconsistent outcome sets during composition rather than on an exporter thread.
The schema has channel-specific validation methods:
- context and resource attributes are checked against their own registered sets;
- an operation checks both its name and operation attributes;
- a metric lookup returns its
MetricSpec, then validates only that metric's dimensions; - an event checks its name and event attributes; and
- an outcome checks membership and permits a failure category only with a registered error outcome.
This distinction is important. A name permitted for trace correlation is not automatically a metric
dimension. In particular, bound TelemetryContext is never copied onto metrics, preventing a changing
request or job identifier from silently multiplying metric series.
2. Values become immutable envelopes¶
TelemetryContext, OperationSpec, MetricObservation, EventObservation, and ResourceIdentity are
frozen dataclasses. The attributes() helper turns a mapping or iterable into a validated, sorted tuple
of unique (name, value) pairs.
Using immutable values gives the implementation three useful properties:
- validation happens once at construction;
- an operation can safely snapshot its context on entry; and
- recording adapters can return snapshots without exposing mutable internal state.
This is not deep immutability for arbitrary objects: the public attribute algebra deliberately permits only bounded strings, booleans, signed integers, finite floats, and tuples of bounded strings. The limited algebra is what makes an envelope safe to validate, sort, record, and translate.
3. The composition root selects a runtime¶
TelemetryRuntime.create() is the single selection boundary:
flowchart TD
A[TelemetryRuntime.create] --> E{config.enabled?}
E -->|no| N[_NoopRuntime]
E -->|yes| I[Validate identity and instance override]
I --> L[Lazy import telemetry.otel]
L --> O[Construct OpenTelemetryRuntime]
O --> F[Return facade]
Disabled configuration returns a facade over _NoopRuntime immediately. The optional SDK module is not
imported. Enabled configuration validates the final resource identity, resolves an optional instance ID
override, requires an exact environment match, and only then loads the production adapter.
The public TelemetryRuntime remains a facade after construction. Consumers do not need to know which
adapter was selected, and hook, flush, and shutdown failures are contained at one process boundary. The
optional adapter_factory parameter is a narrow test seam; production code normally lets the factory
resolve OpenTelemetryRuntime lazily.
4. Binding scopes correlation with ContextVar¶
Both the recording and production adapters keep a private ContextVar[TelemetryContext]. Entering
bind(child) merges parent and child attributes by name, with child values winning. Exiting resets the
exact prior value using the token returned by ContextVar.set().
This gives nested async tasks normal Python context propagation without a process-global correlation
dictionary. It does not automatically propagate into arbitrary new threads. For a controlled
zero-argument thread callback, TelemetryRuntime.wrap_thread_target() captures copy_context() at
wrapper creation and runs the callback inside that captured context.
Operations snapshot context when their context manager is entered. Events read the active context when the log handler emits them. Metrics intentionally ignore bound context and accept only their registered observation dimensions.
5. An operation context manager owns completion¶
Telemetry.operation(spec) returns an OperationScope context manager. The operation begins with the
registered success outcome. The caller may select another registered outcome with
set_outcome(). On exceptional exit, the adapter forces the failure outcome, records only the
exception class name, and returns False so the business exception propagates unchanged.
In the recording adapter, completion appends a CompletedOperation under a lock. In the production
adapter, entry starts a span with merged context and operation attributes; exit sets status, outcome,
and optional failure category before ending it. The same public protocol therefore supports strict
contract tests and fail-open production delivery without changing Consumer instrumentation code.
6. Observations dispatch by closed variant¶
Observation is the union of MetricObservation and EventObservation. The production adapter uses
that closed distinction to select the translation:
| Input | Validation | OpenTelemetry output |
|---|---|---|
MetricObservation |
Registered metric plus its dimensions | Lazily cached counter, up/down counter, or histogram call |
EventObservation |
Registered event plus event attributes | Python log record carrying event.name and safe extras |
Metric instruments are created on first use and cached by name behind a lock. Events pass through the
standard logging path so configured logger levels still apply. The OTLP handler exports a registered
event name—or the fixed body application.log—instead of an arbitrary formatted message.
Production validation and SDK errors are caught at the observation boundary. The individual signal may
be dropped, but telemetry failure does not become business failure. By contrast, RecordingTelemetry
raises validation errors so a Consumer contract test fails immediately.
7. Privacy is enforced again at translation and delivery¶
The design uses defense in depth rather than treating schema validation as the only filter:
- schema construction rejects forbidden key families and high-cardinality metric identities;
- envelope construction bounds names, values, sequences, and counts;
- SDK span limits and the bounded log handler constrain emitted data;
_PrivacyPreservingSpanExportercopies spans while removing raw URLs, headers, and exception details immediately before trace export; and- the Collector deletes unsafe keys, limits attributes, normalizes resource identity, and drops signals without required resource fields before fan-out.
These layers address different sources. The schema controls explicit platform envelopes; the exporter wrapper also protects spans created by framework instrumentation; the Collector protects every producer that reaches the supported gateway. Collector processing is key-based and does not scan arbitrary values or log bodies, which is why the earlier boundaries remain necessary.
8. The Collector processes once, then fans out¶
collector/base.yaml defines the common trace, metric, and log intake. Each signal passes through
memory limiting, resource normalization, required-identity filtering, safety transformation, and
batching. Traces also receive deterministic head sampling in stateless compositions; logs below INFO
are filtered; metrics are unsampled.
The final common-pipeline exporter is a signal-specific forward connector. Backend fragments receive
from those connectors in separate pipelines with separate exporters, retry windows, and sending queues.
flowchart LR
RX[OTLP receiver] --> SAFE[Common bounded safety path]
SAFE --> SAMPLE[Signal-specific sampling or filtering]
SAMPLE --> BATCH[Batch]
BATCH --> FWD[Forward connector]
FWD --> QA[Backend A queue and retry]
FWD --> QB[Backend B queue and retry]
QA --> A[Backend A]
QB --> B[Backend B]
The placement is a correctness property: unsafe attributes are removed once before every destination, and stateless trace sampling makes one decision before fan-out. A failed backend branch can fill or retry its own bounded queue without sharing an exporter queue with another branch.
Persistent and tail-sampling profiles change topology without weakening that base contract. Persistent profiles replace selected exporter queues with file-backed queues, yielding bounded at-least-once delivery. Tail sampling splits routing from stateful trace decisions; metrics and logs remain at the routing tier and never enter the trace sampler.
Runtime lifecycle and failure containment¶
Startup is strict because a partially configured observability subsystem is an operator error. After a runtime starts successfully, delivery is fail-open because exporter or instrumentation failure must not change business behavior.
The production adapter owns everything it creates: providers, exporters, the OTLP log handler, an optional console handler, FastAPI instrumentors, SQLAlchemy listeners, logger-level changes, and at most one lifecycle worker. Partial startup unwinds those owned resources before re-raising the startup error.
Shutdown first marks the runtime closed, then removes hooks and handlers, restores logger levels, and flushes and stops providers. One monotonic deadline is shared across provider work. Third-party provider shutdown methods do not all accept a timeout, so the implementation runs lifecycle work on one daemon thread and bounds how long the caller waits. It never starts a second worker while a timed-out worker is still alive.
Diagnostics deliberately bypass Python logging. Each fixed failure category is written to file descriptor 2 at most once per module and contains no exception message, endpoint, signal value, or credential. That avoids recursive OTLP logging and bounds local noise during a sustained outage.
Framework adapters¶
FastAPI and SQLAlchemy integration are explicit composition-root calls; configuration switches do not scan the process for framework objects.
instrument_fastapi(app) passes the owned tracer and meter providers, substituting explicit no-op
providers when the corresponding signal is disabled. It disables header capture and ASGI send/receive
spans, applies excluded routes, records object identity to prevent duplicate instrumentation, and owns
uninstrumentation at shutdown.
instrument_engine(engine) does not use generic SQL statement instrumentation. It installs three
SQLAlchemy event listeners that create a fixed database.query client span containing only
db.system.name, status, and an exception class when needed. Active spans are keyed by execution
context under a lock. SQL text, parameters, URLs, comments, exception messages, and stack traces never
enter that path.
Performance evaluation implementation¶
The telemetry.performance package uses the same themes—immutable contracts, structural ports, bounded
execution, and safe evidence—but it is a separate subsystem.
PerformanceEvaluator freezes the supplied cases and Measurements, validates unique identities and
execution bounds, and hashes the ordered case names. For each repetition it derives a trial seed,
optionally shuffles a list of case indexes, performs warmups, times successful algorithm calls, then
passes an immutable tuple of in-process observations to every Measurement.
flowchart LR
C[Private Evaluation Cases] --> W[Warmups]
W --> T[Timed algorithm trial]
T --> O[In-process observations]
O --> M[Consumer Measurements]
M --> S[Trial scores and summaries]
S --> R[Payload-free Evaluation Report]
R --> CMP[Compatible report comparison]
CMP --> RULE[Consumer Assessment Rules]
CaseMeasurement adapts one observation-at-a-time function and then aggregates its finite scores.
CorpusMeasurement gives a function all successful observations for a trial. The more general
Measurement protocol permits Consumer-defined implementations without subclassing or registration.
Failures retain stage, exception class, and safe indexes or Measurement names, never exception messages
or case payloads. A complete report has all requested executions and Measurement scores; incomplete
evidence becomes partial or failed. Comparison rejects incompatible evaluation names, case-set
fingerprints, plans, Measurement names, units, or improvement directions. Assessment treats incomplete
evidence as unavailable, never as a pass.
Report writing uses a temporary file in the destination directory, flushes and fsyncs it, then uses
os.replace() for an atomic handoff. Loading checks the input size before parsing and reconstructs the
validated immutable model rather than trusting decoded dictionaries.
Design patterns used—and the pressure each one addresses¶
The implementation uses patterns where they make a boundary explicit. The names below describe the current code; they are not requirements to introduce additional classes.
| Pattern | Concrete use | Problem solved |
|---|---|---|
| Ports and adapters | Telemetry, _RuntimeAdapter, Measurement, and AssessmentRule protocols with recording, no-op, OpenTelemetry, and Consumer implementations |
Keeps domain-facing contracts independent of SDKs and inheritance hierarchies |
| Facade | TelemetryRuntime |
Presents one lifecycle API while containing adapter failures and hiding provider details |
| Factory Method at the composition-root boundary | TelemetryRuntime.create() |
Selects disabled or enabled construction and delays optional imports and side effects |
| Null Object | NoopTelemetry and _NoopRuntime |
Makes disabled behavior branch-free for callers and genuinely side-effect free |
| Immutable Value Object | Frozen schemas, configuration, envelopes, reports, and results | Centralizes invariants and makes snapshots, comparison, and concurrent reads predictable |
| Context Manager | Bindings, operations, and TelemetryRuntime itself |
Couples entry/exit behavior so context restoration, operation completion, and shutdown are difficult to forget |
| Adapter | OpenTelemetry, _OtelLogHandler, CaseMeasurement, and CorpusMeasurement |
Translates one stable contract into an SDK, logging, or callable-specific representation |
| Decorator | _PrivacyPreservingSpanExporter wrapping a concrete exporter |
Adds a mandatory privacy transformation without changing protocol-specific exporters |
| Strategy | Measurement implementations and Assessment Rules | Selects variable algorithms behind a stable calling contract |
| Pipeline | Collector processor order and performance trial stages | Makes ordering constraints visible and independently verifiable |
| Fan-out with bulkheads | Forward connectors plus per-backend queues/retries | Shares safe preprocessing while isolating destination failures |
| Snapshot / Recording Test Double | RecordingTelemetry.operations() and .observations() |
Tests Consumer contracts deterministically without an SDK or network |
Why structural protocols are a good fit¶
Telemetry, Measurement, and AssessmentRule describe behavior rather than shared storage or
lifecycle implementation. Python structural Protocol types let an implementation conform by shape,
so Consumers can supply a small domain-specific object without inheriting from a framework base class.
This keeps dependency direction inward: the code that consumes the port owns its definition.
Why the no-op is more than a convenience¶
Returning a Null Object means application code can always call bind, operation, observe, and
lifecycle hooks. More importantly, selection happens before importing the optional adapter. A disabled
runtime is therefore not merely an enabled runtime that drops exported data; it never constructs the
SDK machinery in the first place.
Why validation is split across constructors and adapters¶
Frozen value constructors enforce local shape and bounds. TelemetrySchema enforces cross-value policy
such as membership and channel vocabulary. The strict recording adapter exposes violations to tests,
while the production adapter catches conversion failures after startup. This division permits early
feedback in development and failure isolation in production without maintaining two public models.
Why the exporter wrapper is a decorator¶
Framework instrumentation can create spans outside OpenTelemetry.operation(). Filtering only the
platform operation adapter would miss those spans. Wrapping the final SpanExporter applies the same
privacy transformation to every span immediately before protocol-specific export while delegating
flush and shutdown to the wrapped exporter.
Why Collector fan-out behaves like bulkheads¶
The term bulkhead describes failure containment, not a special Collector component. Every backend pipeline has its own exporter queue and retry state. The common connector can feed several destinations, but saturation or authentication failure in one destination does not make the healthy destination use the same failing queue. The common intake can still become the shared bottleneck, so this is isolation, not a claim of unlimited availability.
A testing pattern for Consumer instrumentation¶
Consumer code should depend on Telemetry, not construct SDK spans directly. A contract test can then
use the strict recording adapter:
recording = RecordingTelemetry(schema)
with recording.bind(TelemetryContext(attributes({"job.id": "job-42"}))):
with recording.operation(OperationSpec("job.run")) as operation:
operation.set_outcome("accepted")
recording.observe(
MetricObservation(
"job.runs",
1,
attributes({"job.outcome": "accepted"}),
)
)
assert recording.operations()[0].outcome == "accepted"
assert recording.observations()[0].observation.name == "job.runs"
This proves vocabulary, context, outcome, and observation behavior without mocking the subject under test. Separate repository contract tests then prove that the production adapter maps the same public values to OpenTelemetry correctly.
How to change the implementation safely¶
Start at the boundary whose contract changes:
- a public type or validation rule begins in
core.py, its unit tests, and specification Chapters 2–3; - configuration begins in
config.py, configuration tests, and Chapter 4; - lifecycle or framework behavior begins in
runtime.pyorotel.py, hardening/contract tests, and Chapters 5–6; - Collector behavior begins in the affected YAML, static and Docker verification, and Chapters 7–9;
- performance evaluation begins in
telemetry.performance, its unit tests, andperformance-evaluation.md; and - packaging, compatibility, or evidence begins in the scripts/workflow and Chapters 10–11.
Preserve the ownership boundary while editing: Consumers define meaning; the platform owns generic
mechanics and the safety floor. Prefer an observable contract test at the lowest layer and use the
testing feedback ladder to widen verification. Update compatibility.toml when the public
contract, OpenTelemetry dependency range, Collector configuration contract, or pinned artifact identity
changes.
Important non-patterns¶
Several familiar mechanisms are intentionally absent:
- there is no global runtime, provider registry, or service locator;
- there is no automatic discovery of FastAPI apps, SQLAlchemy engines, or thread pools;
- there is no repository abstraction around Collector backends—the YAML fragments are deployment composition artifacts;
- there is no retry loop in application business code; retry and queue policy live at export and Collector boundaries;
- there is no exactly-once claim for persistent delivery; and
- there is no generic “event dictionary” escape hatch around
TelemetrySchema.
Those absences keep lifecycle ownership visible, optional dependencies lazy, telemetry meaning closed, and delivery failures outside the business path.