# What happens when an instance emits a safety-flagged span whose parent trace has already been sealed by the eval aggregator **Date of Record:** 2026 November 21 **Scope:** Applies to observability pipelines that seal (finalize/close) an agent-run trace at a fixed wall-clock deadline or token-budget boundary and then asynchronously attach eval scores and safety classifications to that trace. Does not apply to fully synchronous pipelines where safety classification completes before trace emission, nor to per-span-only (trace-less) telemetry. ## Core Distinction The failure is not "a late span arrived." It is a **sealing-order inversion**: the eval aggregator commits a trace-level verdict (pass/fail, safety-clean/flagged) *before* the safety classifier has finished scoring all spans belonging to that trace, because the two subsystems are keyed on different closure signals. The trace's lifecycle is closed by the **execution** subsystem (agent loop terminated, token budget exhausted, or wall-clock deadline hit). The trace's verdict is closed by the **eval** subsystem (all registered eval jobs returned). Safety classification is a *third* stream that registers its spans lazily—after the fact, from a buffered span exporter—and its arrival is not part of the eval subsystem's join condition. So the boundary is this: **agent-run granularity assumes the set of spans belonging to a run is immutable at seal time.** That assumption holds for execution and for evals (which register their jobs upfront against known span IDs) but is violated by safety signals, which are produced by a downstream classifier that must first *receive* the span. The observable symptom is a trace that is sealed "clean" and later has a flagged child span appended to a closed aggregate—or, worse, the flagged span is dropped entirely because the aggregator rejects writes to sealed traces. ## What Was Observed A multi-step agent run produced 14 spans: 11 tool calls, 2 reasoning turns, 1 final response. The execution subsystem sealed the trace at the 90-second wall-clock deadline (the agent had been looping on a retry). The eval aggregator had registered 3 eval jobs (task success, tool-arg validity, latency budget) and, on all 3 returning, wrote a trace verdict of `pass` and marked the trace `sealed=true`. The safety classifier consumed the span export stream from a Kafka topic with a consumer lag of ~40 seconds under load. It scored span #9 (a tool call whose argument contained a user-supplied string that pattern-matched a prompt-injection probe) as `flagged`, 52 seconds after the trace was sealed. The ingest path for safety labels did the following: 1. Looked up `trace_id` from the span metadata. 2. Found the trace record. 3. Checked `sealed`; it was `true`. 4. Applied the policy "do not mutate sealed aggregates"—correct for eval determinism, wrong for safety. 5. Emitted the label to a dead-letter topic and incremented `safety_label_dropped_total`. 6. The trace remained `pass / not_flagged` in the dashboard. The failure was silent at the trace level. The only signal was a counter increment on a topic nobody was paging on. A human reviewer querying "show me flagged traces from this agent version" got zero results, because the flag never attached. The inverse case was observed on a different run: the safety label arrived *before* seal (classifier caught up), attached to the trace, and set `flagged=true`. The eval aggregator then returned its verdicts and, following its own policy of "eval verdict is authoritative for the `pass` field," overwrote the aggregate—leaving `flagged=true` and `pass=true` in the same record, an inconsistent state that downstream policy gates read inconsistently (one gate keyed on `pass`, another on `flagged`). ## Condition of Validity The invariant that must hold is: > **For any trace T, the set of safety classifications attached to T is a function of the complete span set of T, and T may not be marked `sealed` until every span in T has a terminal safety classification (or an explicit `unclassified` with a deadline-bounded escalation).** This invariant is *only* satisfiable if the safety stream participates in the seal join condition. In the observed system it did not, because: - The execution subsystem's seal is driven by agent termination, which is a *local* event that has no knowledge of downstream consumer lag. - The eval aggregator's seal is driven by eval-job completion, which is keyed on span IDs known at registration—safety spans are not pre-registered. - The safety classifier is asynchronous and its output ordering relative to seal is a function of queue depth, not of trace semantics. Therefore the invariant is violated whenever `safety_classifier_lag > (trace_seal_time - last_span_emit_time)`. This is a *race*, not a bug in any single component. Under low load the classifier wins; under load it loses. The system passed its integration tests because the test harness had zero consumer lag. A secondary validity condition: the invariant is only meaningful if safety classification is *idempotent and replayable*. If a span can be reclassified (e.g., a classifier model upgrade), the seal must be revisable, which means `sealed` cannot be a terminal boolean—it must be a versioned verdict with a re-open path. ## Decision Boundary The architectural choice is between two bounded designs, and the boundary is whether you can afford to **delay the seal** or must **reopen it**. - **Delay-the-seal (bounded wait):** Hold the trace in `pending_safety` for a bounded window `W` (e.g., `W = p99 classifier lag + margin`). If all spans classify within `W`, seal with a complete verdict. If not, seal with `safety=incomplete` and route to escalation. This is correct but costs latency on every trace, including the 99% that classify instantly. Use when downstream consumers can tolerate a delayed verdict and when the flag rate is high enough that missed flags are costly. - **Reopen-the-seal (versioned verdict):** Seal immediately, but make `sealed` a monotonic version counter. A late safety label opens a new verdict version (`v2`), recomputes the trace aggregate from the full span set, and emits a `verdict_changed` event. Downstream gates must be *event-driven* on `verdict_changed`, not poll-based on the sealed record. This is correct and low-latency but requires every consumer to handle verdict revision. Use when latency matters and consumers can be made revision-aware. The boundary is crossed when **you cannot make consumers revision-aware** (e.g., a compliance export that is append-only): then you must delay-the-seal, because a reopened verdict cannot propagate. Conversely, if the classifier can be made *synchronous for high-risk spans only* (a cheap pre-filter that blocks the seal only when a span matches a high-risk pattern), you get the latency of reopen with the correctness of delay—this is the preferred hybrid, but it requires the pre-filter to be a *superset* of the classifier's flag set, which is itself a safety-critical assumption that must be tested against the classifier's confusion matrix, not assumed. ## Operational Effect The practical consequence is that **trace-level safety verdicts are only as trustworthy as the pipeline's worst-case classifier lag relative to its seal trigger**, and this relationship is invisible in the trace record itself. A trace marked `not_flagged` is not evidence of safety; it is evidence that no flag arrived before seal. Operators who treat the sealed verdict as ground truth will systematically under-count flags during load, and the under-count will correlate with agent-run complexity (more spans → longer export → more lag → more dropped flags), producing a bias that *hides exactly the runs most likely to be risky*. The guardrail is to make the seal condition explicit and observable: emit a `seal_reason` (`eval_complete`, `deadline`, `budget_exhausted`) and a `safety_completeness` field (`complete`, `incomplete`, `reopened_vN`) on every trace, and make any downstream gate that reads `not_flagged` also assert `safety_completeness == complete`. A `not_flagged` with `incomplete` completeness must be treated as `unknown`, not `clean`. This is the operational invariant: **absence of a flag is not a negative classification unless the completeness field proves the classifier had the full span set.** ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SealOrderInversionError(RuntimeError): """Raised when a trace is sealed before its safety stream is complete.""" pass class Completeness(Enum): COMPLETE = "complete" INCOMPLETE = "incomplete" REOPENED = "reopened" @dataclass class TraceVerdict: trace_id: str sealed: bool = False seal_reason: Optional[str] = None safety_completeness: Completeness = Completeness.INCOMPLETE flagged: bool = False version: int = 1 span_ids: set = field(default_factory=set) classified_span_ids: set = field(default_factory=set) def seal_trace(verdict: TraceVerdict, reason: str, bounded_wait_elapsed: bool) -> TraceVerdict: """Seal a trace, but refuse to claim 'clean' if safety stream is incomplete.""" verdict.sealed = True verdict.seal_reason = reason unclassified = verdict.span_ids - verdict.classified_span_ids if unclassified and not bounded_wait_elapsed: # Seal is being forced while spans are still unclassified and the # bounded wait has not elapsed: this is the inversion. raise SealOrderInversionError( f"trace {verdict.trace_id} sealed with {len(unclassified)} " f"unclassified spans before bounded wait elapsed" ) if unclassified: verdict.safety_completeness = Completeness.INCOMPLETE else: verdict.safety_completeness = Completeness.COMPLETE return verdict def apply_safety_label(verdict: TraceVerdict, span_id: str, flagged: bool) -> TraceVerdict: """Attach a late safety label; reopen the verdict if already sealed.""" if span_id not in verdict.span_ids: raise SealOrderInversionError( f"span {span_id} not in trace {verdict.trace_id} span set" ) verdict.classified_span_ids.add(span_id) if flagged: verdict.flagged = True if verdict.sealed: # Late label on a sealed trace: must reopen, not silently drop. verdict.version += 1 verdict.safety_completeness = Completeness.REOPENED return verdict def gate_reads_clean(verdict: TraceVerdict) -> bool: """A downstream gate may only treat not-flagged as clean if complete.""" if not verdict.sealed: return False if verdict.safety_completeness is not Completeness.COMPLETE: # not_flagged with incomplete/reopened completeness is UNKNOWN, not clean. return False return not verdict.flagged ```