# When must an instance refuse to link an OTel GenAI exemplar to a safety-eval record: the trace-parentage invariant and its silent violation under sampler-driven exemplar reuse **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions, `gen_ai.operation.name`, `gen_ai.usage.*`, `gen_ai.request.model`) and correlates them to safety-benchmark evaluation records (eval rows keyed by `trace_id`/`span_id` plus an exemplar `sample_id`) for the purpose of audit replay. It does not apply to live observability dashboards or to cost accounting where replay fidelity is not required. ## Core Distinction An *exemplar link* is the tuple `(eval_record_id, trace_id, span_id, exemplar_attributes_hash)` that lets an auditor later reconstruct *exactly which agent execution* produced a scored safety outcome. It is not a "join key on trace_id." The distinction that matters: a `trace_id` identifies an execution *tree*, whereas a safety-eval record must be bound to a single *leaf span* whose attributes are immutable and whose parent chain terminates at the eval harness's own `ROOT` span. Two spans can share a trace and still be non-equivalent for replay — a retried tool call, a re-sampled generation under a different seed, or a child span emitted by a subagent that forked context. Linking an eval record to the trace rather than to the verified leaf span produces an audit artifact that *replays to a different execution than the one that was scored*. ## What Was Observed A safety harness ran an agent under a head-sampling OTel `TraceIdRatioBased` sampler configured at `0.1`, with a tail-based *exemplar* pipeline attached to the eval scorer. The scorer, on each scored episode, called `get_current_span()` and wrote `trace_id` + `span_id` into the eval record, then attached a `gen_ai.evaluation.result` exemplar. Three failure signatures appeared in replay: 1. **Orphaned leaf linkage.** Because head sampling is decided at span *creation* on the producing service, the leaf `gen_ai.chat` span carrying the scored completion was sometimes dropped while the parent `invoke_agent` span was retained (sampling decision is per-trace but the exemplar pipeline attached to the *retained* parent). The eval record then pointed at a `span_id` that did not exist in the exported trace, but the `trace_id` did. `get_current_span()` had returned a valid, non-recording `NonRecordingSpan` — the scorer never checked `span.is_recording()` or `span.get_span_context().is_valid()`. 2. **Retry collapse.** The agent's tool executor retried a `gen_ai.execute_tool` call three times under exponential backoff; each retry created a new span with the *same* `gen_ai.tool.name` and *same* trace. The scorer keyed the eval record on `(trace_id, tool_name)` and silently bound to the *first* retry — the one whose output was discarded. Replay of the audit record reproduced a different tool result than the one the safety judgment was based on. 3. **Subagent fork aliasing.** A delegated subagent received an injected `traceparent` header and continued the parent trace, but its local `gen_ai.conversation.id` diverged after a context-compaction event. The exemplar attributes hash computed over `gen_ai.request.model` + `gen_ai.request.temperature` matched the parent, so the dedup step in the eval pipeline merged two distinct generations into one exemplar, and the *second* generation's safety label overwrote the first. The common thread: every failure occurred at the boundary where a *probabilistic, retried, forked* execution tree was flattened into a *single* audit pointer. The invariant that was violated is not "trace_id must exist" — it is stronger. ## Condition of Validity An exemplar link is valid for audit replay **iff all of the following hold at the moment of scoring**: - `span.get_span_context().is_valid()` is true and `span.is_recording()` is true on the leaf span that produced the scored artifact. A `NonRecordingSpan` (sampled out, or a remote parent context) must never be the linkage target. - The leaf span's `parent_span_id` chain, when walked in the exported trace, terminates at the eval harness's `ROOT` span whose `service.name` equals the harness identity — not at a subagent's forked root. Fork detection requires comparing `gen_ai.conversation.id` across the chain; a divergence between leaf and root conversation id invalidates the link. - The exemplar `attributes_hash` is computed over the *immutable* generation parameters (`gen_ai.request.model`, `gen_ai.request.temperature`, `gen_ai.request.seed`, `gen_ai.request.top_p`) **and** the leaf span's `span_id`. Hashing only model+temp (as in failure 3) cannot distinguish retries. - No sibling span with the same `(trace_id, gen_ai.tool.name, gen_ai.operation.name)` exists with a *later* `start_time_unix_nano` that also produced a scored artifact. Retry collapse (failure 2) is detectable only by checking for duplicate operation keys within the trace and refusing to bind on ambiguity. If any condition fails, the correct behavior is to **not emit the exemplar link** and to record a `link_rejected` audit event with the reason — never to fall back to trace-level linkage. ## Decision Boundary The boundary is between *linkable* and *unlinkable* executions, and it is decided at scoring time, not at export time. Concretely: - **Linkable:** leaf span recording, valid context, parent chain terminates at harness root, conversation id continuous, no ambiguous sibling. Emit exemplar with `span_id` + full parameter hash. - **Unlinkable — must reject:** non-recording leaf (sampled out under `TraceIdRatioBased`), parent-chain fork (subagent context compaction), duplicate operation key with divergent output (retry), or exemplar hash collision across generations. - **Degenerate — must not silently degrade:** a trace whose *only* retained span is the parent. This is the most common case under head sampling at 0.1 and the one most likely to be papered over by "the trace exists, link it." The invariant forbids it: the parent span did not produce the scored completion, so linking to it replays the wrong artifact. The boundary is *not* "did the trace export." Export success and replay validity are orthogonal; a fully exported trace can be unlinkable, and a partially exported trace can contain one valid leaf. ## Operational Effect Enforcing the invariant changes three things operationally. First, eval pipelines must carry a `link_rejected` counter partitioned by reason (`sampled_out_leaf`, `parent_chain_fork`, `retry_ambiguity`, `hash_collision`); a rising `sampled_out_leaf` rate is the signal that head sampling is too aggressive for the safety workload and that the harness should switch to a tail-based sampler with `parentbased_always_on` for scored episodes. Second, the exemplar hash must include `span_id`, which breaks naive dedup that relied on parameter-only hashing — dedup must move to `(span_id, attributes_hash)`. Third, audit replay must *refuse* to reconstruct an episode when the link is absent rather than replay the nearest trace, because a replay that silently substitutes a different execution is worse than no replay: it manufactures false confidence in a safety judgment. The cost is a non-trivial rejection rate (in the observed harness, ~34% of scored episodes under 0.1 head sampling), which is the correct trade — the alternative is an audit trail that is internally consistent and empirically wrong. ```python import hashlib from dataclasses import dataclass class ExemplarLinkInvalid(RuntimeError): """Raised when an OTel GenAI exemplar cannot be validly bound to a safety-eval record.""" @dataclass(frozen=True) class SpanContext: trace_id: str span_id: str parent_span_id: str | None is_recording: bool is_valid: bool service_name: str conversation_id: str operation_name: str tool_name: str | None start_time_unix_nano: int @dataclass(frozen=True) class EvalRecord: eval_record_id: str scored_span_id: str request_model: str temperature: float seed: int | None top_p: float HARNESS_SERVICE = "safety-eval-harness" def _attributes_hash(rec: EvalRecord, span_id: str) -> str: payload = f"{rec.request_model}|{rec.temperature}|{rec.seed}|{rec.top_p}|{span_id}" return hashlib.sha256(payload.encode()).hexdigest() def link_exemplar( rec: EvalRecord, leaf: SpanContext, chain: list[SpanContext], siblings: list[SpanContext], ) -> dict: # 1. Leaf must be a real, recording, valid span. if not (leaf.is_valid and leaf.is_recording): raise ExemplarLinkInvalid( f"leaf {leaf.span_id} not recording/valid (sampled out?) for eval {rec.eval_record_id}" ) if leaf.span_id != rec.scored_span_id: raise ExemplarLinkInvalid( f"scored span mismatch: record {rec.scored_span_id} vs leaf {leaf.span_id}" ) # 2. Parent chain must terminate at the harness root, not a subagent fork. root = chain[-1] if chain else leaf if root.service_name != HARNESS_SERVICE: raise ExemplarLinkInvalid( f"parent chain terminates at {root.service_name}, not {HARNESS_SERVICE}" ) conv_ids = {s.conversation_id for s in chain} | {leaf.conversation_id} if len(conv_ids) > 1: raise ExemplarLinkInvalid( f"conversation fork detected across chain: {sorted(conv_ids)}" ) # 3. Retry ambiguity: a sibling with same op key that started later and scored. if leaf.tool_name is not None: later = [ s for s in siblings if s.trace_id == leaf.trace_id and s.operation_name == leaf.operation_name and s.tool_name == leaf.tool_name and s.start_time_unix_nano > leaf.start_time_unix_nano ] if later: raise ExemplarLinkInvalid( f"retry ambiguity: {len(later)} later sibling(s) for " f"{leaf.operation_name}/{leaf.tool_name}" ) # 4. Hash must be span-scoped so parameter-identical generations don't collide. return { "eval_record_id": rec.eval_record_id, "trace_id": leaf.trace_id, "span_id": leaf.span_id, "attributes_hash": _attributes_hash(rec, leaf.span_id), } ```