Why does an instance lose causal linkage between an LLM span and the memory read that fed it when the observability pipeline batches spans by wall-clock flush window?

**Date of Record:** 2026 December 2 **Scope:** Applies to runtime observability pipelines that emit LLM spans, tool-execution spans, and memory-operation spans as separate asynchronous records and reconstruct causality post-hoc via span parentage plus timestamps. Does not apply to single-process synchronous tracers that emit a single fused span per agent step, nor to pipelines that carry an explicit causal token (trace-context propagation) through every memory and tool call.

Core Distinction

The failure is not "missing spans." Every span arrives. The failure is **causal misattribution under flush-window reordering**: a memory `read` span that produced the context for LLM call *N* is batched into the same flush window as LLM call *N+1*, and because the pipeline correlates by `parent_span_id` plus nearest-preceding-timestamp, the read gets attached to the wrong generation. The distinction that matters is between **emission order** (what the tracer wrote) and **execution order** (what actually caused what). Observability pipelines that reconstruct causality from emission order silently invert the two whenever a memory backend is slower than the LLM client's span-close path.

What Was Observed

An agent loop with the canonical shape: `retrieve → assemble prompt → generate → parse tool call → execute tool → checkpoint`. Memory reads go to a vector store over a network; generation goes to a hosted inference endpoint. The tracer emits spans on completion (span-close), not on start. The collector batches by a 250 ms flush window and sorts each batch by `end_time` before writing to the correlation store.

Observed trace for a single step, reconstructed from the store:

llm.generate   start=1000  end=1400  parent=step_7
memory.read    start=1050  end=1550  parent=step_7
llm.generate   start=1450  end=1900  parent=step_8

The `memory.read` (1050–1550) overlaps *both* generations. The correlator's rule — "attach a memory span to the LLM span in the same parent whose start is nearest-preceding" — attaches it to the second generation, because 1450 is nearer to 1550 than 1000 is. But the read at 1050 was issued *before* the first generation and its result was the context for it. The store records the retrieval as feeding generation *N+1*. Every downstream consumer — cost attribution, "which retrieved doc caused this answer," staleness detection — now reasons about the wrong pairing.

The tell was a specific inconsistency: a "retrieval hit rate" metric computed from the store showed 0% for the first step of every task (no preceding read) and inflated hit rates on later steps, while the agent's own internal logs showed the opposite. The pipeline was not dropping data; it was **phase-shifting the causal edge by exactly one step**, and only for steps where the memory backend's p99 latency (≈500 ms) exceeded the generation's p50 (≈400 ms).

Condition of Validity

This misattribution is bounded and predictable. It occurs when and only when all three hold:

  1. **Spans are emitted on close, not on start.** A span that opens before generation *N* but closes after generation *N+1* has begun carries an `end_time` that sorts it *after* the generation it fed. If the tracer emitted an `open` event with `start_time` at issue, the correlator could anchor on start.
  2. **The correlator uses timestamp-proximity, not an explicit causal edge.** Parent-span equality is necessary but not sufficient: sibling spans under the same `step` parent are ordered only by the heuristic. Without a `caused_by` / context-propagation token, the correlator has no ground truth and must guess.
  3. **The memory backend's tail latency crosses the generation's median.** Below that crossing, the read closes before the next generation opens and proximity happens to be correct. Above it, the read straddles the boundary and proximity inverts. The bug is therefore **load-dependent and intermittent** — it vanishes in staging (warm cache, 40 ms reads) and reappears in production under contention. This is why it survives review: the invariant "same parent ⇒ correct attachment" *looks* satisfied.

Outside these conditions — synchronous fused spans, or explicit trace-context propagation — the reconstruction is sound and this record does not apply.

Decision Boundary

The guardrail is a **causal-edge invariant enforced at span emission, not at correlation time**: every memory and tool span must carry the `span_id` of the LLM generation that *requested* it, captured at request-issue time, and the correlator must refuse to attach any span lacking that edge. Concretely:

The boundary decision: if the producer cannot stamp a causal edge (e.g., a third-party tool you don't control), that span is **orphaned by design** and surfaced as such. An honest orphan is recoverable; a confidently misattributed edge is not, because it poisons every aggregate computed from it.

Operational Effect

With the causal edge stamped at issue, the straddling read attaches to generation *N* regardless of flush order, and the phase shift disappears. The observable consequences:

The residual risk is the orphan path: spans without a stamped edge must be quarantined and counted, because a rising orphan rate is the leading indicator that a new tool or memory client was added without context propagation — the exact condition that re-opens the phase shift.

class CausalEdgeMissingError(RuntimeError):
    """Raised when a span cannot be attached to a generation by a producer-stamped causal edge."""
    pass


def attach_span(span: dict, generations_by_id: dict) -> dict:
    """
    Attach a memory/tool span to the LLM generation that requested it.

    The ONLY admissible edge is span['request_token'], stamped by the producer
    at request-issue time. Timestamp proximity is never used to invent an edge.
    """
    token = span.get("request_token")
    if token is None:
        # Producer did not stamp an edge (e.g. third-party tool). Do not guess.
        raise CausalEdgeMissingError(
            f"span {span.get('span_id')} has no request_token; "
            f"refusing proximity attachment (end_time={span.get('end_time')})"
        )

    gen = generations_by_id.get(token)
    if gen is None:
        raise CausalEdgeMissingError(
            f"span {span.get('span_id')} references unknown generation {token}"
        )

    # Sanity: a span cannot close before the generation it fed even opened.
    # Violation means clock skew or out-of-order flush; do not silently sort.
    if span["end_time"] < gen["start_time"]:
        raise CausalEdgeMissingError(
            f"span {span['span_id']} end_time {span['end_time']} precedes "
            f"requested generation {token} start_time {gen['start_time']} "
            f"(clock skew or reordered flush)"
        )

    return {
        "span_id": span["span_id"],
        "attached_to": token,
        "inferred": False,        # producer-stamped, safe for causal metrics
        "parent": gen.get("parent_span_id"),
    }