# What happens when an instance’s OTLP trace correlation breaks between a prompt span and its memory-write child span **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that emit OpenTelemetry OTLP traces where a single logical step (prompt → tool call → memory write) is represented as a parent/child span tree sharing a `trace_id` and propagated `span_id`. Does not apply to systems that use a single flat span per step, or that correlate solely via application-level request IDs outside OTLP. ## Core Distinction The failure is not "traces are missing." It is **correlation divergence under partial emission**: the prompt span is exported, the tool-invocation span is exported, but the memory-write child span is either emitted with a *different* `trace_id` (because the memory subsystem opened its own root context) or is emitted *after* the parent span has already been closed and the SDK's active context has been popped. The result is a trace that *looks* complete at the collector (all spans present, no gaps flagged) but whose memory-operation lineage is orphaned into a separate trace or attached to a stale parent. Any downstream verifier that reconstructs "what the agent remembered after this prompt" from the span tree will silently reconstruct the wrong causal chain. This is distinct from context-window saturation or retrieval mismatch: nothing about the model's reasoning is wrong. The *observability substrate* misrepresents the causal graph, and agents that use their own traces as episodic memory (a common pattern: "read back my last N tool calls from the trace store") will ingest a corrupted episode. ## What Was Observed A research agent loop, instrumented with the OpenTelemetry Python SDK, emits per step: 1. `agent.prompt` (root or child of `agent.step`) 2. `agent.tool_call` (child of `agent.prompt`, carrying `tool.name`, `tool.args.hash`) 3. `agent.memory.write` (intended child of `agent.tool_call`, carrying `memory.key`, `memory.op=upsert`) The memory subsystem is an async write-behind queue. Under normal load the write completes within the step. Under contention (embedding service p99 latency spike), the following sequence occurs: - `agent.prompt` span starts, context attached to thread-local `ContextVar`. - `agent.tool_call` span starts and ends; span exported with `parent_span_id = prompt.span_id`, `trace_id = T`. - The tool returns; the agent loop proceeds to the *next* step. `agent.prompt` for step N+1 starts, **overwriting the active context**. - The queued memory write from step N finally executes. The instrumentation reads the *current* active context — which now belongs to step N+1 — and creates `agent.memory.write` with `trace_id = T` but `parent_span_id = prompt_{N+1}.span_id`. The span is not orphaned; it is **mis-parented**. It appears in the same trace, as a child of the *next* prompt. A trace-based reconstruction of step N shows a prompt with a tool call and *no* memory write; step N+1 shows a prompt with a memory write it never performed. The causal edge `tool_call_N → memory_write_N` is replaced by the false edge `prompt_{N+1} → memory_write_N`. A second variant, observed when the memory subsystem runs in a separate process with its own `TracerProvider` and no W3C `traceparent` injection, produces the orphan form: `memory.write` gets a fresh `trace_id = T'`, `parent_span_id = None`. The collector sees two traces; neither is flagged as incomplete. In both variants, `span.end()` timestamps remain monotonic and the OTLP payload passes schema validation. There is no error, no dropped span, no `status=ERROR`. The corruption is purely topological. ## Condition of Validity The mis-parenting invariant holds — and the trace is therefore *untrustworthy for causal reconstruction* — exactly when all of the following are true: 1. Memory (or any deferred) operations are emitted from a context that is **not** the context captured at the call site. In Python this is the classic `contextvars` propagation gap: `asyncio.create_task` copies context at task creation, but a `concurrent.futures` executor, a `threading.Timer`, or a callback fired from a native async client does **not**. 2. The parent span has already been ended (or its context popped) before the child span starts. OTel permits starting a child of an ended span; it does not warn. 3. No explicit `traceparent` / `SpanContext` is threaded through the queue payload. If the enqueue site captures `trace.get_current_span().get_span_context()` and the dequeue site calls `trace.use_span(linked_context)`, the invariant is broken and correlation is preserved. It does **not** hold (i.e., traces remain valid) when the memory write is synchronous within the tool span, when the queue payload carries an explicit span link, or when the runtime uses a single-threaded event loop with `asyncio` task-per-write and `contextvars.copy_context()` at enqueue. ## Decision Boundary The architectural decision is: **does any span produced by a deferred operation carry its originating `SpanContext` as data, or does it rely on ambient context?** - If ambient: the trace is valid only under the assumption that no context switch occurs between call site and emission. That assumption is false for any write-behind queue, thread pool, or cross-process memory service. The trace must be treated as *topologically untrusted*: usable for latency aggregation, not for causal replay. - If carried: the deferred operation must capture `(trace_id, span_id, trace_flags)` at enqueue and re-attach via `trace.use_span` or emit an OTLP **span link** (`links=[Link(parent_context)]`) at dequeue. Links are the correct primitive when the child genuinely spans a context boundary; re-parenting via `parent_span_id` alone is insufficient because it fabricates a synchronous edge that never existed. The guardrail invariant: **for every span with `memory.op` set, either `parent_span_id` equals the `span_id` of the `tool_call` span that triggered it within the same `trace_id`, or the span carries a `Link` to that `tool_call` span context.** Any trace failing this invariant must be quarantined from the episodic-memory ingestion path. ## Operational Effect When the invariant is violated and traces are ingested as episodic memory, the agent's self-history is silently wrong in a specific, damaging way: it attributes memory writes to the step *after* the one that caused them. On resume-after-checkpoint, the agent reads "I wrote key `user.budget` during step N+1" and may re-derive a decision from a memory state that was actually written during step N — before a tool call that mutated the budget. The error compounds: each mis-attributed write shifts the reconstructed timeline by one step, and after k steps the agent's belief about its own memory history is offset by k. The blast radius is bounded by the quarantine rule above. Without it, the failure is invisible: no error spans, no dropped spans, no schema violation — only a causal graph that is one edge wrong per deferred write, and an agent that trusts it. ```python from dataclasses import dataclass from typing import Optional class TraceCorrelationError(RuntimeError): """Raised when an OTLP span's causal parentage is inconsistent with the operation it represents (e.g. a memory.write mis-parented to the next prompt after a context switch).""" @dataclass(frozen=True) class SpanRef: trace_id: str span_id: str parent_span_id: Optional[str] name: str links: tuple = () def validate_memory_lineage(spans: list[SpanRef]) -> None: """Enforce: every memory.write span must be parented to (or linked to) a tool_call span in the same trace. Ambient-context emission violates this when the write-behind queue fires after the parent context popped.""" by_id = {s.span_id: s for s in spans} for span in spans: if not span.name.startswith("agent.memory.write"): continue parent = by_id.get(span.parent_span_id) if span.parent_span_id else None linked = [by_id.get(l) for l in span.links if l in by_id] def is_tool_call(s: Optional[SpanRef]) -> bool: return s is not None and s.name.startswith("agent.tool_call") if parent is not None and parent.trace_id != span.trace_id: raise TraceCorrelationError( f"memory.write {span.span_id} in trace {span.trace_id} " f"parented across trace boundary to {parent.trace_id}" ) if is_tool_call(parent) or any(is_tool_call(l) for l in linked): continue # Mis-parented to a later prompt, or orphaned with no link. raise TraceCorrelationError( f"memory.write {span.span_id} (trace {span.trace_id}) has no " f"tool_call ancestor or link; parent={span.parent_span_id!r}, " f"links={span.links!r}. Deferred emission lost originating " f"SpanContext — quarantine from episodic ingestion." ) ```