# Where must an instance bound the replay of a GenAI semantic-convention trace before a span reorder silently rewrites the agent's causal history **Date of Record:** 2026 November 27 **Scope:** Applies to deterministic replay of agent execution traces captured under OpenTelemetry GenAI semantic conventions where replay reconstructs causal order from span timestamps and parent/child links. Does not apply to traces captured with an explicit monotonic causal sequence token (e.g., a Lamport counter or vector clock) embedded in every span attribute. ## Core Distinction The naive assumption is that a GenAI semantic-convention trace is a faithful, ordered log: each `gen_ai.*` span records a model call, tool invocation, or retrieval step, and replaying the trace in timestamp order reproduces the agent's reasoning path. This conflates *wall-clock observation order* with *causal execution order*. In a real agent, spans are emitted by multiple asynchronous emitters—the orchestrator, the tool sandbox, the retrieval service, and the LLM gateway—each stamping `start_time_unix_nano` from its own clock. The span *finish* timestamp and the parent span's *start* timestamp can interleave in ways that are not causally possible, because the tool span's clock is skewed relative to the orchestrator's clock, or because a child span's `end` lands before its parent's `start` after NTP correction. Replay that sorts purely on timestamps then reconstructs a history the agent never executed: a tool result appearing before the prompt that requested it, a model completion preceding the retrieval it conditioned on. The invariant that must hold is: **replay order must be derived from the parent/child span graph plus a monotonic causal key, never from raw timestamp sort alone.** Timestamps are observational metadata; the span tree is the causal skeleton. When the two disagree, the tree wins and the timestamps are demoted to annotations. ## What Was Observed A multi-step research agent emitted, per task, an orchestrator span (`agent.run`), one `gen_ai.chat` span per model turn, and one `execute_tool` span per tool call. The tool sandbox ran in a separate container whose clock was corrected by chrony roughly every 64 seconds. During a 40-minute task, a chrony step of −1.8 s occurred on the sandbox host between the model turn that emitted the tool call and the tool span that carried it out. The raw trace, after collection, showed: - `gen_ai.chat` span (turn 3) — `start=...T00:12:04.100`, `end=...T00:12:07.400`, parent = `agent.run` - `execute_tool` span (the call requested by turn 3) — `start=...T00:12:05.900` (skewed −1.8 s, so the true instant was 00:12:07.700), `end=...T00:12:06.300`, parent = `gen_ai.chat` (turn 3) On a naive timestamp sort, `execute_tool` begins at 00:12:05.900, *before* the `gen_ai.chat` turn 3 span ends at 00:12:07.400. Worse, the tool span's `end` (00:12:06.300) precedes the chat span's `end`, so a replayer that reconstructs "the model finished thinking, then the tool ran" instead reconstructs "the tool ran while the model was still generating"—a state the agent never occupied. The replay then attributes the tool's output to the wrong reasoning turn, and the subsequent distillation step (episodic→semantic memory) records a false causal edge: *the tool result informed turn 3's generation*, when in fact turn 3's generation produced the tool call. The corrupted edge propagates into every later replay of that task and into any memory distilled from it. The parent/child links were correct throughout. The `execute_tool` span's `parent_span_id` pointed at the turn-3 chat span. Only the timestamps lied. ## Condition of Validity The guardrail holds—replay reproduces true causal order—only under all of the following: 1. Every span carries a valid `parent_span_id` forming a tree rooted at the `agent.run` span, with no orphaned tool spans (tool spans emitted by a sandbox that failed to propagate context are orphans and must be quarantined, not timestamp-sorted into the stream). 2. A monotonic causal key exists that is invariant to clock steps. The acceptable keys are, in order of preference: an explicit sequence attribute stamped by the orchestrator at span creation (`agent.seq`), a Lamport counter propagated in span attributes, or—failing both—the parent-child depth-first traversal order of the span tree, which is monotonic *within a single parent's children* but not across siblings from different emitters. 3. When two sibling spans under the same parent have overlapping or inverted timestamp intervals, the replayer does not break the tie by timestamp. It breaks the tie by the causal key, and if no causal key exists, it flags the pair as *causally ambiguous* and refuses to emit a total order for that subtree. If condition 2 cannot be met—no sequence attribute, no counter—the replay is not deterministic and must be labeled as such. A replay labeled deterministic that silently falls back to timestamp sort is the failure mode this record exists to prevent. ## Decision Boundary The boundary is sharp: **a replayer may sort by timestamp only within a set of spans that share a single emitter and a single parent.** The moment a span set spans two emitters (orchestrator and sandbox, gateway and retriever), timestamp sort is invalid and the causal key or tree traversal must take over. Concretely: - Same parent, same emitter, non-overlapping intervals → timestamp sort is safe and equivalent to causal order. - Same parent, different emitters → timestamp sort is unsafe; use causal key; if absent, mark subtree ambiguous. - Different parents at different tree depths → never compare timestamps across the boundary; tree order is authoritative even if the child's timestamp precedes the parent's start (clock skew) or follows the parent's end (async completion). - A tool span whose `end` precedes its parent's `start` → this is a skew artifact, not a causal inversion; replay must clamp the tool span's effective interval into the parent's interval and record the skew magnitude as an annotation, not reorder. The decision to *accept* a replay as ground truth for downstream memory distillation requires that the fraction of causally ambiguous subtrees be zero. A single ambiguous subtree means the distilled memory may contain a false causal edge, and the distillation must be withheld or the subtree replayed under an explicit assumption flag. ## Operational Effect Without the guardrail, the failure is silent and cumulative. The trace looks well-formed; every span validates against the semantic-convention schema; the replay runs without error. The corruption surfaces only downstream, when an agent retrieves a distilled memory that encodes "tool result preceded its requesting turn" and uses it to plan a task—repeating a tool call whose result it already had, or skipping a retrieval because memory says the retrieval happened after the generation it was meant to inform. The agent's behavior degrades in a way that is untraceable to the original clock step, because the clock step was laundered into a memory edge. With the guardrail, the replayer refuses to fabricate order: it emits a causal tree with explicit ambiguity annotations, the distillation gate rejects any task whose ambiguity count is nonzero, and the skew magnitude is logged so the operator can see the sandbox clock discipline problem at its source rather than three replays later. The cost is that some traces become unreplayable as ground truth—which is correct. An unreplayable trace is a known unknown; a falsely replayed trace is an unknown unknown that poisons memory. ## Enforcement The following replayer enforces the invariant at the point where it would otherwise fall back to timestamp sort. It raises rather than silently ordering. ```python from dataclasses import dataclass, field from typing import Optional class CausalReplayAmbiguity(RuntimeError): """Raised when replay would order spans by timestamp across emitter boundaries without a monotonic causal key, fabricating a causal history.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] emitter: str # e.g. "orchestrator", "sandbox", "gateway" start_ns: int end_ns: int seq: Optional[int] = None # orchestrator-stamped monotonic key, if present def order_children(parent: Span, children: list[Span]) -> list[Span]: """Order the children of a single parent. Timestamp sort is permitted only when all children share one emitter; otherwise a causal key is required.""" if not children: return [] emitters = {c.emitter for c in children} has_key = all(c.seq is not None for c in children) if len(emitters) == 1: # Single emitter: timestamps are causally reliable within it. return sorted(children, key=lambda c: (c.start_ns, c.span_id)) if has_key: # Multi-emitter: the monotonic key is authoritative; timestamps demoted. return sorted(children, key=lambda c: (c.seq, c.span_id)) # Multi-emitter, no causal key: refuse to fabricate an order. raise CausalReplayAmbiguity( f"parent {parent.span_id} has children from emitters {sorted(emitters)} " f"with no monotonic causal key; timestamp sort would fabricate causal order. " f"children={[c.span_id for c in children]}" ) def replay(root: Span, spans: list[Span]) -> list[str]: """Depth-first causal replay. Returns span_ids in causal order or raises.""" by_parent: dict[Optional[str], list[Span]] = {} for s in spans: by_parent.setdefault(s.parent_span_id, []).append(s) ordered: list[str] = [] def visit(node: Span) -> None: ordered.append(node.span_id) kids = by_parent.get(node.span_id, []) # A tool span whose interval precedes its parent is a skew artifact; # clamp it into the parent interval rather than reorder. for k in kids: if k.start_ns < node.start_ns: k.start_ns = node.start_ns for child in order_children(node, kids): visit(child) visit(root) return ordered ```