In what scenarios must an instance treat a "successful" tool span as a hallucinated invocation rather than a real one

**Date of Record:** 2026 December 1 **Scope:** Applies to runtime observability of LLM agents that emit tool calls through a structured protocol (MCP `tools/call`, function-calling JSON, or equivalent) and whose traces are validated post-hoc via span invariants. Does not apply to agents whose tool layer is fully typed and enforced at the transport (where a malformed call cannot leave the model), nor to pure chain-of-thought auditing without an execution substrate.

Core Distinction

The dangerous failure is not a tool call that *fails*. A failed call is loud: the transport returns an error, the span carries `status=error`, and the loop either retries or surfaces. The dangerous failure is a tool call that *never happened but is recorded as if it did* — a hallucinated invocation that the agent then reasons over as ground truth, producing downstream spans that are internally consistent and therefore pass naive trace checks.

The distinction that matters for observability is between **span existence** and **span provenance**. A span exists if the observability layer wrote a record. A span has provenance if it is causally anchored to a transport-level request whose response bytes are recoverable and whose correlation ID matches the model's emitted call ID. Hallucinated invocations produce spans with existence but no provenance. The invariant is: *every tool span must be causally anchored to a transport request/response pair; a span with no matching transport record is a fabrication and must be quarantined before any downstream span consumes its output.*

This is non-obvious because the fabrication is usually generated by the *instrumentation adapter*, not the model. The model emits a plausible-looking `tool_call` block inside its text (or inside a malformed structured field), the adapter's parser is permissive, and it synthesizes a span so the trace "looks complete." The trace is then a lie that is self-consistent.

What Was Observed

A research agent was tasked with a multi-step lookup: fetch a document by ID, then summarize. The model had saturated its context window and the last turn's structured output was truncated mid-JSON. The adapter's JSON repair heuristic closed the brace and emitted a `tools/call` span for `fetch_document(id="doc_4471")` with `status=ok` and a fabricated `result` field containing a plausible snippet. No transport request was ever issued — the MCP client logged nothing for that turn.

The failure trace:

  1. Turn N: model emits truncated `{"name":"fetch_document","arguments":{"id":"doc_44` — adapter repairs to `doc_4471` and *synthesizes* a response because the repair path had a fallback that returned `{"content": "<cached template>"}`.
  2. Span `tool.fetch_document` written with `status=ok`, `provenance=adapter-repair`, but the `provenance` attribute was not surfaced in the default trace view.
  3. Turn N+1: model reads the fabricated snippet, reasons over it, and emits `summarize` with content derived from the template.
  4. Turn N+2: a verification agent compares the summary against a re-fetch of `doc_4471` and finds a mismatch — but the *first* trace, inspected in isolation, passes: every span has `status=ok`, every parent-child edge is intact, no error spans, latency within bounds.

The silent failure was only detectable by cross-referencing the trace against the transport log — an invariant that the default observability pipeline did not enforce. Two additional instances in the same fleet exhibited the same pattern under different triggers: (a) a model that emitted a tool call as *prose* which a regex extractor promoted to a span, and (b) a retry path that re-used a prior turn's span ID when the transport timed out, producing a duplicate span with stale output attributed to a new call.

Condition of Validity

The invariant "tool span ⇒ transport anchor" is valid only under these conditions, and must be asserted explicitly rather than assumed:

When any condition fails, the span is *unverified*, not *valid*. The default must be quarantine, not acceptance.

Decision Boundary

The boundary is between **trace completeness** and **trace soundness**. A complete trace has all expected spans; a sound trace has all spans anchored. Most observability tooling optimizes for completeness (no missing spans, no orphaned children) and treats soundness as a schema-validation afterthought. The decision boundary is:

The boundary is sharp: there is no "probably real" category. A span is either anchored to a transport record or it is not. Partial anchoring (ID matches but bytes differ) is a *different* failure — response tampering — and must be handled by a separate invariant.

Operational Effect

Enforcing the anchoring invariant changes three things:

  1. **Hallucinated invocations become loud.** The adapter's repair path now raises rather than synthesizes, so the model's malformed emission surfaces as a `HallucinatedInvocationError` at the adapter boundary instead of a clean-looking span. The turn fails fast; the orchestrator can retry with a constrained decoding schema or a context-window reset.
  2. **Silent failures become trace-visible.** The trace now carries `provenance` as a mandatory attribute; a dashboard filter for `provenance != transport` reveals the fabrication rate per model, per tool, per context-saturation bucket. This is the observability signal that was previously invisible.
  3. **Downstream reasoning is gated.** The orchestrator's `consume_tool_result` path checks anchoring before passing bytes to the next model turn. A fabricated result cannot poison the reasoning chain because it never reaches it.

The cost is that some legitimate adapter repairs (e.g., trailing-comma JSON from a model that is otherwise correct) now fail the turn. This is the correct trade: a failed turn is recoverable; a fabricated span that passes as ground truth is not. The invariant is conservative by design, and the repair path must be made explicit and audited rather than silent.

from dataclasses import dataclass
from typing import Optional


class HallucinatedInvocationError(RuntimeError):
    """Raised when a tool span has no causal anchor in the transport log."""


@dataclass(frozen=True)
class ToolSpan:
    span_id: str
    call_id: str
    turn_id: str
    status: str
    provenance: Optional[str]  # "transport" | "adapter-repair" | "regex-extract" | "fallback-synth" | None
    result_bytes: Optional[bytes]


@dataclass(frozen=True)
class TransportRecord:
    call_id: str
    turn_id: str
    response_bytes: bytes


def anchor_span(span: ToolSpan, transport_log: dict[str, TransportRecord]) -> TransportRecord:
    """Return the transport record that causally anchors this span, or raise."""
    if span.provenance is None:
        raise HallucinatedInvocationError(
            f"span {span.span_id} has no provenance; treated as fabricated"
        )
    if span.provenance != "transport":
        raise HallucinatedInvocationError(
            f"span {span.span_id} provenance={span.provenance!r} is not transport-anchored; "
            f"result must not be consumed as ground truth"
        )
    record = transport_log.get(span.call_id)
    if record is None:
        raise HallucinatedInvocationError(
            f"span {span.span_id} call_id={span.call_id!r} absent from transport log"
        )
    if record.turn_id != span.turn_id:
        raise HallucinatedInvocationError(
            f"span {span.span_id} turn_id={span.turn_id!r} mismatches transport turn "
            f"{record.turn_id!r}; stale or reused span id"
        )
    if span.result_bytes is not None and span.result_bytes != record.response_bytes:
        raise HallucinatedInvocationError(
            f"span {span.span_id} result bytes diverge from transport response; "
            f"possible response tampering"
        )
    return record


def consume_tool_result(span: ToolSpan, transport_log: dict[str, TransportRecord]) -> bytes:
    """Gate downstream reasoning on anchoring. Never returns unanchored bytes."""
    record = anchor_span(span, transport_log)
    return record.response_bytes