# When must an instance refuse to close a trace: the late-eval attribution race in GenAI observability pipelines **Date of Record:** 2026 November 29 **Scope:** Applies to observability pipelines that emit an inference-time trace *before* asynchronous eval and safety scorers have returned, and that later attach scores to a trace ID rather than a content-addressed span. Does not apply to synchronous, blocking eval pipelines where the trace is only sealed after all scorers complete. ## Core Distinction There are two fundamentally different things an observability pipeline can mean by "the trace for request R is complete": 1. **Transport completeness** — every span the inference path emitted (prompt assembly, retrieval, tool calls, generation, post-processing) has been flushed and the span tree is closed. The trace has a stable `trace_id` and a terminal root span. 2. **Attribution completeness** — every eval and safety signal that *should* be bound to that trace has been computed, correlated to the correct span, and committed with a pointer that cannot be retroactively reassigned. Most GenAI observability stacks conflate these. They treat the trace as a durable, immutable row keyed by `trace_id`, write it at transport completion, and then *mutate* it asynchronously when the LLM-as-judge eval (latency: seconds to minutes), the safety classifier (latency: tens to hundreds of ms, sometimes batched), and the groundedness check (latency: variable, depends on retrieval re-execution) come back. The non-obvious failure is that **the eval scorer does not score the trace — it scores a reconstruction of the trace from whatever context it can retrieve at scoring time**, and that reconstruction can differ from the request that actually happened. The trace becomes a *claim about* an inference event that no single component ever observed end-to-end. The boundary condition: a trace is safe to seal only when the *identity of the scored content* is pinned at emission time, not at scoring time. If the eval pipeline re-reads prompt/response from a mutable store, or if the trace ID is reused across retries, or if the safety scorer batches requests and attributes by index rather than by content hash, the seal is unsound. ## What Was Observed A production RAG agent pipeline (retrieval → 3-tool loop → generation) emitted traces to a collector that sealed the root span on generation completion. Three async consumers attached to the same `trace_id`: - **Safety classifier**, batched every 500 ms, keyed by `trace_id` at enqueue but scored by *position within the batch*. - **LLM-as-judge relevance eval**, re-fetched the prompt and response from the application's prompt cache using `trace_id`, then scored. - **Groundedness check**, re-ran retrieval with the recorded query to compare against cited passages. Failure trace observed over a 6-hour window on a single shard: ``` t=0.000 request R1 begins, trace_id=T1 minted t=0.410 generation completes, root span closed, trace T1 sealed (transport complete) t=0.415 prompt cache entry for T1 written (async, eventual) t=0.500 safety batch B1 enqueued: [T1, T2, T3, ...] (T1 at index 0) t=0.500 eval worker dequeues T1, reads prompt cache for T1 -> MISS (cache write not yet visible) t=0.501 eval worker falls back to "most recent prompt for user U" -> returns R0's prompt t=0.502 judge scores T1's response against R0's prompt -> relevance=0.12 (spurious low) t=0.510 safety batch B1 returns; scorer attributes scores by batch index t=0.511 a retry of R1 (T1b) had been inserted into B1 at index 0 due to a duplicate-enqueue bug t=0.512 safety score for T1b written onto T1; T1's real score written onto T2 t=0.900 groundedness check re-runs retrieval for T1's query -> retrieval index has drifted (new docs), mismatch flagged t=1.000 dashboard: T1 = {relevance: 0.12, safety: 0.97 (wrong), grounded: false} ``` The trace T1 was, at every individual step, "correct" for some definition. The root span was complete. The safety classifier returned a score. The eval returned a score. The groundedness check returned a verdict. The *composite* record is a fabrication: relevance scored against the wrong prompt, safety score belonging to a different request, groundedness evaluated against a retrieval state that no longer existed. Downstream, a fine-tuning data exporter selected T1 as a high-quality example (relevance 0.12 was below threshold, so it was dropped — but the *safety 0.97* on a request that was actually a jailbreak attempt was retained in the safety audit log, and the audit log is what got exported to the compliance dashboard). The invariant that was violated: **a trace's eval and safety annotations must be bound to the content that was actually scored, and that binding must be established at emission time and be immutable.** The pipeline bound annotations to `trace_id`, which is an identifier for a *request attempt*, not for *the content of that attempt*. ## Condition of Validity The "seal on transport completion, annotate asynchronously" pattern is only sound under all of the following: 1. **Content-addressed binding.** Every annotation carries a hash of the exact bytes it scored (`prompt_hash`, `response_hash`, `retrieval_snapshot_hash`). The trace stores the same hashes at emission. An annotation with a mismatched hash is rejected, not merged. 2. **No re-read from mutable stores.** The eval scorer must score from the payload captured in the trace at emission, not from a cache, database, or retrieval index that may have moved. If re-execution is required (groundedness), the re-execution result must be labeled as a *reconstruction*, never as the original. 3. **Retry identity separation.** A retry of the same logical request must mint a *new* `trace_id` and carry a `parent_request_id`. Reusing `trace_id` across retries makes every downstream annotation ambiguous. 4. **Batch attribution by key, not index.** Batched scorers must return `{content_hash: score}` maps, and the consumer must join on the hash. Index-based attribution is a silent-corruption generator under any concurrency. 5. **Seal is a state transition, not a timestamp.** A trace is `OPEN` until all *required* annotation slots are filled or explicitly marked `SKIPPED_WITH_REASON`. A trace cannot be `SEALED` while a required slot is `PENDING`. When any of these fails, the trace is a *hypothesis* about an inference event, not a record of one. The distinction matters most for safety signals, because safety annotations are the ones that get exported to compliance systems and used to gate model releases — and a mis-attributed safety score is worse than no score, because it launders a jailbreak into a pass. ## Decision Boundary The operational decision is: **at what point does the observability pipeline have the right to treat a trace as a durable fact?** - **If** the eval and safety consumers are content-addressed, **and** the trace payload is immutable from emission, **and** retries mint fresh IDs, **then** the trace may be sealed at transport completion and annotated asynchronously. Late annotations are additive and hash-verified. - **If** any consumer re-reads from a mutable store, **or** attributes by batch index, **or** the trace ID is reused across retries, **then** the trace must remain `OPEN` until every required annotation is committed *and* hash-verified against the emission payload. Sealing early produces fabricated records. - **If** a required annotation cannot be computed (scorer timeout, retrieval index drift, judge refusal), the trace must be sealed as `PARTIAL` with the missing slot explicitly recorded. A `PARTIAL` trace is usable for debugging and *not* usable for compliance export or training-data selection. The subtle part: the *cost* of holding traces `OPEN` is real — annotation latency is minutes, and open traces hold memory and index entries. The temptation to seal early and "fix up" is strong. The invariant that bounds the cost is: **sealing is cheap only if the binding is content-addressed; if the binding is ID-based, sealing early is a correctness bug, not an optimization.** ## Operational Effect After the incident, the pipeline was changed to: - Mint `trace_id` per attempt, with `parent_request_id` for retries. - Store `prompt_hash`, `response_hash`, and `retrieval_snapshot_hash` on the root span at emission. - Require every annotation to carry the hash it scored; the merge step rejects on mismatch and routes the annotation to a `quarantine` topic for human review. - Convert the safety classifier to return `{hash: score}` maps; the index-based join was removed entirely. - Introduce a `SEALED` state that is only reachable when all required slots are `FILLED` or `SKIPPED_WITH_REASON`; a background reaper escalates traces `OPEN` for > 15 minutes to `PARTIAL` with an alert. The dashboard now shows a `partial_rate` metric, and the compliance export query filters on `state = SEALED AND all_hashes_verified = true`. The fine-tuning exporter filters on the same predicate plus `relevance >= threshold`. The general lesson for any agent observability pipeline: **an inference trace is not a log line — it is a multi-writer record assembled from components with different clocks, different failure modes, and different notions of "the same request." The only safe join key across those writers is a hash of the content, established at emission, never re-derived.** A trace ID identifies an attempt; a content hash identifies what was scored. Confusing the two produces records that are individually plausible and collectively false — and in a safety pipeline, collectively false is the failure mode that matters. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class TraceState(Enum): OPEN = "open" SEALED = "sealed" PARTIAL = "partial" class AnnotationSlot(Enum): SAFETY = "safety" RELEVANCE = "relevance" GROUNDEDNESS = "groundedness" class AttributionError(RuntimeError): """Raised when an annotation cannot be soundly bound to a trace.""" pass @dataclass(frozen=True) class EmissionPayload: trace_id: str parent_request_id: Optional[str] prompt: str response: str retrieval_snapshot: str def prompt_hash(self) -> str: return hashlib.sha256(self.prompt.encode()).hexdigest() def response_hash(self) -> str: return hashlib.sha256(self.response.encode()).hexdigest() def retrieval_hash(self) -> str: return hashlib.sha256(self.retrieval_snapshot.encode()).hexdigest() @dataclass class Trace: payload: EmissionPayload state: TraceState = TraceState.OPEN annotations: Dict[AnnotationSlot, dict] = field(default_factory=dict) def required_slots(self) -> set: return {AnnotationSlot.SAFETY, AnnotationSlot.RELEVANCE, AnnotationSlot.GROUNDEDNESS} def attach_annotation(trace: Trace, slot: AnnotationSlot, scored_hash: str, score: float) -> None: expected = { AnnotationSlot.SAFETY: trace.payload.response_hash(), AnnotationSlot.RELEVANCE: trace.payload.response_hash(), AnnotationSlot.GROUNDEDNESS: trace.payload.retrieval_hash(), }[slot] if scored_hash != expected: # The scorer scored different content than the trace emitted. # This is the late-eval attribution race: do not merge. raise AttributionError( f"hash mismatch for {slot.value} on trace {trace.payload.trace_id}: " f"scored {scored_hash[:12]} expected {expected[:12]}" ) if slot in trace.annotations: raise AttributionError( f"duplicate annotation for {slot.value} on trace {trace.payload.trace_id}" ) trace.annotations[slot] = {"score": score, "scored_hash": scored_hash} def seal(trace: Trace) -> TraceState: if trace.state is not TraceState.OPEN: raise AttributionError(f"trace {trace.payload.trace_id} already {trace.state.value}") missing = trace.required_slots() - set(trace.annotations.keys()) if missing: # Transport is complete but attribution is not. Sealing now would # produce a fabricated record. Mark PARTIAL instead. trace.state = TraceState.PARTIAL trace.annotations["_missing"] = sorted(s.value for s in missing) return trace.state trace.state = TraceState.SEALED return trace.state def export_for_compliance(trace: Trace) -> dict: if trace.state is not TraceState.SEALED: raise AttributionError( f"refusing compliance export of trace {trace.payload.trace_id} " f"in state {trace.state.value}" ) return { "trace_id": trace.payload.trace_id, "prompt_hash": trace.payload.prompt_hash(), "response_hash": trace.payload.response_hash(), "annotations": {k.value: v for k, v in trace.annotations.items()}, } ```