# Why does an instance's safety-flag span arrive after its cost-telemetry span has already been sealed into an immutable trace batch? **Date of Record:** 2026 November 30 **Scope:** Applies to observability pipelines that emit per-step spans from an agent runtime and join them to (a) cost telemetry and (b) safety-classifier verdicts before sealing a trace into an immutable batch for later correlation. Does not apply to single-process synchronous loggers where all telemetry for a step is emitted within one call frame. ## Core Distinction The failure here is not "the safety signal was wrong" or "the cost number was wrong." It is a **join-timing skew**: two telemetry producers that both describe the *same* agent step commit their records at different points in the step's lifecycle, and the trace-sealing stage freezes the batch at the earlier producer's commit boundary. The cost span is emitted synchronously by the runtime the moment a model call returns (token counts are known). The safety span is emitted asynchronously by a classifier that must read the *full* step output — including any tool-call arguments and the final assistant message — and that classifier is itself an LLM call with variable latency. The core distinction is between **completeness of a step** and **closure of a batch**. A step can be complete (runtime knows it is done) while its safety verdict is still in flight, because the safety verdict is derived from the step output, not produced by it. Pipelines that treat "step complete" as "all spans for this step are present" will seal a batch that is structurally missing a span that will arrive milliseconds later and be dropped as orphaned. ## What Was Observed A cost-telemetry span is emitted at `t0` when the model call returns. Its `trace_id` and `step_id` are minted by the runtime. The safety classifier is invoked at `t1 = t0 + ε` (after the output is assembled), and its span is emitted at `t2 = t1 + Δ`, where `Δ` is the classifier's own LLM latency — typically 200ms to 3s, and heavy-tailed: p99 routinely exceeds 10s under classifier load. The trace batcher seals on a **step-completion watermark**: when the runtime signals that step `N` is done, the batcher flushes all spans whose `step_id ≤ N` into an immutable batch, computes a batch hash, and hands it to the correlation store. The safety span for step `N`, arriving at `t2`, finds its batch already sealed. Two things then happen depending on the batcher's orphan policy: 1. **Drop policy (silent):** the orphaned safety span is discarded. The batch now records cost for step `N` but no safety verdict. Downstream correlation reports "step N: cost $0.0041, safety: unknown." A step that was actually flagged `harmful` reads as `unknown`, and any policy keyed on `safety != harmful` passes it. 2. **Quarantine policy (loud but lossy):** the orphan is parked in a dead-letter queue keyed by `step_id`. Because the batch is immutable, it cannot be amended; the correlation store must be patched with a *second* batch that references the same `step_id`. Now the trace has two batches for one step, and any consumer that assumes one-batch-per-step double-counts cost or, worse, takes the first batch's `safety: unknown` as authoritative and ignores the patch. The observed invariant violation: **for a step whose safety classifier latency Δ exceeds the batch-seal watermark lag W, the sealed batch's safety field is systematically biased toward `unknown`** — and the bias is not random. It concentrates on exactly the steps with the longest outputs (which take the classifier longest to read) and the highest-risk tool calls (which require the most classifier attention). The safety signal is missing precisely where it matters most. A secondary observation: retry amplification. When the classifier is slow, the runtime's step-completion signal may fire while the classifier is still running; some runtimes then *re-invoke* the classifier on retry, producing two safety spans for one step with potentially divergent verdicts (the classifier is non-deterministic). The correlation store sees two `safety` records for one `step_id` and must choose — and the choice is order-dependent, so two consumers reading the same trace can disagree on the verdict. ## Condition of Validity This failure is bounded and does not occur under any of the following conditions, which are the guardrails: - **The batcher seals on a *safety-complete* watermark, not a *step-complete* watermark.** That is, step `N`'s batch is not sealed until either the safety span for `N` arrives or a per-step safety deadline `D_safety` expires. This requires the runtime to emit a *step-open* record at `t0` with a known `step_id`, so the batcher can hold the batch open for that step until the safety span or deadline arrives. - **Safety spans carry a causal parent reference to the cost span** (`parent_span_id`), and the batcher performs a *join* on `step_id` rather than an *append* on arrival order. A join can be deferred; an append cannot. - **The batch is sealed with an explicit `expected_span_types` set** and refuses to seal if any expected type is missing and no deadline has fired. A sealed batch that is missing an expected span type is a *contract violation*, not a normal state. - **Classifier retries are idempotent on `step_id`** — the classifier is invoked with a deterministic seed or a dedup key, so a retry produces the same verdict or is discarded as duplicate, and the correlation store resolves to a single `safety` record per `step_id`. If none of these hold, the failure is live. The condition of validity is therefore: **the batch-seal watermark MUST be the join-completion watermark, not the runtime's step-completion watermark.** Any pipeline that conflates the two will exhibit the skew. ## Decision Boundary The decision boundary is the choice of watermark. Concretely: - **Seal-on-step-complete** (broken): batch closes at `t0 + W`, where `W` is a fixed lag. Valid only if `Δ < W` for all steps, which is false for heavy-tailed classifier latency. This boundary is crossed whenever `p99(Δ) > W`. - **Seal-on-join-complete** (correct): batch closes at `max(t0 + W, t2)` for the latest step in the batch, or at `t0 + D_safety` if the safety span has not arrived. The batch is sealed with an explicit `safety_status ∈ {present, deadline_expired}` field so that `deadline_expired` is a *first-class, auditable* state rather than a silent `unknown`. The boundary is *not* "increase W." Increasing W reduces the frequency of skew but does not eliminate it, because Δ is unbounded (classifier under load, or a classifier that itself retries). The boundary is the *semantic* change from "sealed when the step is done" to "sealed when the join is done or its deadline fired." A second decision boundary: **what to do when the deadline fires.** The two valid policies are (a) seal with `safety_status = deadline_expired` and route the step to a *synchronous re-check* before any downstream action, or (b) block the batch and alert. The invalid policy is to seal with `safety = unknown` and let downstream treat `unknown` as `safe`. The boundary is whether `unknown` is a *terminal* state or a *pending* state. If the correlation schema has no distinction between "no verdict" and "verdict pending," the pipeline cannot be made correct by any watermark change. ## Operational Effect The observable effect is a **systematic, load-correlated under-reporting of safety flags in sealed traces**, concentrated on long-output and high-risk steps, and invisible to any monitoring that aggregates over all steps (because most steps have short outputs and fast classifiers, so the aggregate looks fine). The p50 safety coverage is 99.9%; the p99.9 is where the misses live, and those are the steps that matter. The compounding effect: because cost is present and safety is `unknown`, any *cost-per-flagged-step* or *safety-adjusted-cost* metric computed over sealed batches is biased downward — the pipeline reports fewer flags per dollar than reality, which feeds back into budget and policy decisions. The bias is not a measurement error; it is a *join* error that propagates into every derived metric. The guardrail that bounds it is the **join-completion watermark with an explicit `deadline_expired` state**, plus **idempotent classifier retries keyed on `step_id`**. With these, the sealed batch is a *complete* record of the step (safety either present or explicitly pending), and the correlation store has a single authoritative safety record per step. Without them, the pipeline is correct only for the fast tail of the classifier latency distribution, and the failure is silent, load-correlated, and biased toward the highest-risk steps. ```python import hashlib import time from dataclasses import dataclass, field from typing import Optional class TraceSealViolation(RuntimeError): """Raised when a batch is sealed without a required span type and no deadline fired.""" pass @dataclass class Span: step_id: str span_type: str # "cost" | "safety" payload: dict arrived_at: float @dataclass class Batch: step_ids: list spans: dict = field(default_factory=dict) # span_type -> Span sealed: bool = False safety_status: Optional[str] = None # "present" | "deadline_expired" class JoinCompleteBatcher: """Seals a batch only when the join is complete or the safety deadline fires.""" def __init__(self, safety_deadline_s: float = 5.0): self.safety_deadline_s = safety_deadline_s self._open: dict = {} # step_id -> Batch self._step_open_at: dict = {} def open_step(self, step_id: str, now: Optional[float] = None) -> None: now = now if now is not None else time.monotonic() self._open[step_id] = Batch(step_ids=[step_id]) self._step_open_at[step_id] = now def ingest(self, span: Span) -> None: batch = self._open.get(span.step_id) if batch is None or batch.sealed: # Orphan: span arrived after its batch was sealed. raise TraceSealViolation( f"orphaned {span.span_type} span for sealed step {span.step_id}" ) if span.span_type in batch.spans: # Duplicate (classifier retry). Keep first, drop rest — idempotent on step_id. return batch.spans[span.span_type] = span self._maybe_seal(span.step_id, now=span.arrived_at) def _maybe_seal(self, step_id: str, now: float) -> None: batch = self._open[step_id] has_cost = "cost" in batch.spans has_safety = "safety" in batch.spans opened = self._step_open_at[step_id] deadline_fired = (now - opened) >= self.safety_deadline_s if has_cost and has_safety: batch.safety_status = "present" batch.sealed = True return if has_cost and not has_safety and deadline_fired: batch.safety_status = "deadline_expired" batch.sealed = True return if has_cost and not has_safety and not deadline_fired: return # hold open — do NOT seal on step-complete alone if not has_cost: # Safety arrived but cost never did — this is a contract violation, # not a normal state. Sealing here would silently drop cost. raise TraceSealViolation( f"step {step_id} has safety span but no cost span; " f"refusing to seal incomplete batch" ) def seal_due(self, now: float) -> list: sealed = [] for step_id in list(self._open): self._maybe_seal(step_id, now=now) if self._open[step_id].sealed: sealed.append(self._open.pop(step_id)) return sealed ```