Where must an instance reconcile non-monotonic span timestamps before deterministic replay of an agentic session from OpenTelemetry GenAI logs?
**Date of Record:** 2026 December 2 **Scope:** Applies to replay harnesses that reconstruct agent execution (tool calls, memory reads/writes, LLM invocations) from OTel GenAI spans (`gen_ai.*` semantic conventions) emitted by concurrent or async runtimes. Does not apply to single-threaded synchronous traces where span start/end ordering is guaranteed by the runtime, nor to replay that only consumes a canonical event-sourced journal rather than the span tree.
Core Distinction
The distinction that matters is between **causal order** (which event actually caused which) and **span emission order** (the order timestamps happen to land in the exported batch). Deterministic replay requires the former; OTel GenAI logs reliably provide only the latter. A replay engine that sorts spans by `start_time_unix_nano` and feeds them to a fresh agent instance will reproduce a *plausible* session, not the *observed* one, whenever the agent issued concurrent tool calls, streamed a response while a background memory write was in flight, or ran on a runtime whose clock source is per-thread (Go monotonic clocks, Node `process.hrtime`, Python `asyncio` loop time) and whose exporters batch independently.
The non-obvious failure is **non-monotonic span timestamps under a single `trace_id` with a shared parent**: children of one agent step can arrive with `start_time` earlier than the parent's `start_time`, or with a child's `end_time` preceding a sibling's `start_time` even though the sibling's *effect* (a memory mutation the child read) is causally prior. Sorting by timestamp produces a replay that violates the read-after-write dependency the original session relied on, and the replayed agent then reasons over a state that never existed.
What Was Observed
A session with a single `gen_ai.agent` root span and three children: `gen_ai.tool` (memory read of key `user.preferences`), `gen_ai.chat` (LLM call that consumes the read result), and `gen_ai.tool` (memory write of `user.preferences` triggered by a parallel planner branch). Exported attributes:
- Root `start_time`: `T+0ms`
- Memory-write child `start_time`: `T+2ms`, `end_time`: `T+9ms`
- Memory-read child `start_time`: `T+3ms`, `end_time`: `T+4ms`
- LLM chat child `start_time`: `T+10ms`, `end_time`: `T+140ms`
Timestamp-sorted replay executes read → write → chat. The original execution was write → read → chat: the read observed the *new* preference value. The replayed agent observes the *old* value, produces a different tool-call sequence downstream, and diverges at the first post-read decision. The divergence is silent—no error, no exception, just a different branch—because the replayed agent is internally consistent with the state it was given.
The root cause is not clock skew between hosts (all spans share one process). It is that the memory-write tool was dispatched on an `asyncio` task whose `time.monotonic_ns()` call fired *before* the read task's, but the read task's span was exported in a batch that the SDK flushed earlier. OTel's `BatchSpanProcessor` exports on a timer or queue-size trigger per processor; two processors (one per tracer provider, common when an agent SDK and a tool SDK each register their own) can flush in either order. Timestamps are recorded at span start, but *arrival* at the collector is unordered.
A second observation: `gen_ai.usage.input_tokens` on the chat span was `1840`, but the sum of tokens implied by the three tool outputs visible at `T+10ms` was `1210`. The 630-token gap was the memory-write payload that the read had consumed but that the read span did not carry as an attribute. Replay engines that reconstruct context from span attributes alone (rather than from the tool-call argument/result pairs the agent actually saw) will under-fill the context window and change the model's behavior at temperature 0.
Condition of Validity
Timestamp-sorted replay is valid only if all of the following hold for the session:
- **Single-writer causal chain.** No two spans under the same `trace_id` touch the same memory key, tool resource, or external endpoint without an explicit `link` attribute (`SpanLink`) recording the dependency.
- **Monotonic parent-child containment.** For every span `s` and its parent `p`, `p.start_time ≤ s.start_time` and `s.end_time ≤ p.end_time`. This is *not* guaranteed by the OTel spec and is routinely violated by async runtimes.
- **Complete attribute capture at span start.** The tool result must be present on the span (as `gen_ai.tool.call.result` or equivalent) *before* any downstream span that consumed it started. If the downstream span started before the result was recorded, the result is not recoverable from the span tree alone.
- **Deterministic tool outputs.** Any tool whose output is non-deterministic (clock, RNG, network) must carry the observed output as an attribute; otherwise replay re-executes and diverges.
If any condition fails, the replay must not proceed by timestamp sort. It must either reconstruct order from `SpanLink` edges and tool-result attributes, or refuse to replay and emit a divergence record.
Decision Boundary
The boundary is between **replayable** and **replayable-with-reconstruction**, and it is crossed the moment the harness detects a non-monotonic edge or an unresolved causal dependency.
Concretely: before feeding spans to the replayed agent, the harness computes a partial order. Edges come from (a) parent-child containment where it holds, (b) `SpanLink` attributes, (c) explicit `gen_ai.tool.call.id` → `gen_ai.tool.result.id` pairing, and (d) memory-key read-after-write on spans that carry `gen_ai.memory.key` and `gen_ai.memory.op`. If the resulting DAG has a cycle, or if a read span's key was written by a span that is *not* an ancestor in the DAG, the harness must halt and emit a `ReplayOrderViolation` rather than pick a timestamp tiebreak. A timestamp tiebreak on a non-monotonic edge is the single decision that converts a detectable divergence into a silent one.
The second boundary: if the replayed agent's context at any step differs from the reconstructed context by more than a configurable token delta (observed case: 630 tokens), the replay is classified as **state-divergent** even if the token-level output matches, because the match is coincidental. Determinism claims require context equality, not output equality.
Operational Effect
The operational consequence is that a replay harness built on OTel GenAI logs cannot treat the span tree as a total order. It must treat it as a partial order plus a set of unresolved edges, and it must fail closed on unresolved edges. Teams that skipped this step reported replay divergence rates of 8–14% on multi-tool sessions, with the divergences concentrated in sessions where a planner branch and an executor branch shared a memory key. After adding the DAG reconstruction and the fail-closed check, divergence dropped to the residual caused by non-deterministic tool outputs (which the harness now records and replays from attributes, not re-executes).
The guardrail is architectural, not statistical: **no replay step may execute before its causal predecessors are resolved, and an unresolved predecessor is a hard error, never a timestamp guess.** This is the invariant that keeps a replay harness honest about what it can and cannot reproduce.
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable
class ReplayOrderViolation(RuntimeError):
"""Raised when the span tree cannot be linearized into a valid causal order."""
@dataclass(frozen=True)
class Span:
span_id: str
parent_id: str | None
start_ns: int
end_ns: int
kind: str # "agent" | "chat" | "tool" | "memory"
memory_key: str | None = None
memory_op: str | None = None # "read" | "write"
links: tuple[str, ...] = field(default_factory=tuple)
tool_call_id: str | None = None
tool_result_for: str | None = None
def linearize(spans: Iterable[Span]) -> list[Span]:
"""Return spans in a causal order, or raise if the order is ambiguous.
Ordering rules, in priority:
1. parent -> child (only when containment holds)
2. explicit SpanLink edges
3. tool_call_id -> tool_result_for pairing
4. memory write -> read on the same key (write must precede read)
Timestamps are used ONLY as a tiebreak among spans with no causal edge
between them. A timestamp tiebreak across a causal edge is a violation.
"""
spans = list(spans)
by_id = {s.span_id: s for s in spans}
edges: dict[str, set[str]] = {s.span_id: set() for s in spans}
for s in spans:
if s.parent_id and s.parent_id in by_id:
p = by_id[s.parent_id]
if p.start_ns <= s.start_ns and s.end_ns <= p.end_ns:
edges[p.span_id].add(s.span_id)
for link in s.links:
if link in by_id:
edges[link].add(s.span_id)
if s.tool_result_for and s.tool_result_for in by_id:
edges[s.tool_result_for].add(s.span_id)
writes = {s.memory_key: s for s in spans if s.memory_op == "write" and s.memory_key}
for s in spans:
if s.memory_op == "read" and s.memory_key in writes:
w = writes[s.memory_key]
if w.span_id != s.span_id:
edges[w.span_id].add(s.span_id)
indeg = {sid: 0 for sid in edges}
for src, dsts in edges.items():
for d in dsts:
indeg[d] += 1
ready = [sid for sid, d in indeg.items() if d == 0]
ready.sort(key=lambda sid: (by_id[sid].start_ns, sid))
order: list[Span] = []
while ready:
sid = ready.pop(0)
order.append(by_id[sid])
for d in edges[sid]:
indeg[d] -= 1
if indeg[d] == 0:
ready.append(d)
ready.sort(key=lambda x: (by_id[x].start_ns, x))
if len(order) != len(spans):
unresolved = [by_id[sid] for sid, d in indeg.items() if d > 0]
raise ReplayOrderViolation(
"cycle or unresolved causal edge among spans: "
+ ", ".join(s.span_id for s in unresolved)
)
# Verify no causal edge is reversed by the timestamp tiebreak.
pos = {s.span_id: i for i, s in enumerate(order)}
for src, dsts in edges.items():
for d in dsts:
if pos[src] >= pos[d]:
raise ReplayOrderViolation(
f"causal edge {src}->{d} reversed by linearization"
)
return order
def replay(step_fn, spans: Iterable[Span]) -> None:
try:
order = linearize(spans)
except ReplayOrderViolation as exc:
raise ReplayOrderViolation(f"refusing to replay: {exc}") from exc
for span in order:
step_fn(span)