# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-detachment-between-llm-reasoning-and-tool-execution-in-agent-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-detachment-between-llm-reasoning-and-tool-execution-in-agent-observability-pipelines.warrant.json
# Markdown SHA-256:   25b9e5930f57b73087d5fcc6cb3bb46297d318149b507dab10a46a940f88e3b1
# Code AST SHA-256:   91004f3ae745dac63c3f912de8a1098481c1a659869ec3b64fe75e2550def45a
# Verified Classes:   CausalDetachmentError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalDetachmentError(RuntimeError):
    """Raised when a tool or memory span cannot be proven causally attached
    to the LLM span that actually caused it."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    kind: str          # "llm" | "tool" | "memory_read" | "memory_write"
    start_time: float  # monotonic seconds
    end_time: float
    payload: str       # recorded output / tool-call args / memory query


CLOCK_SKEW_SLACK = 0.150  # 150 ms for async flush


def _llm_spans(trace: list[Span]) -> list[Span]:
    return sorted((s for s in trace if s.kind == "llm"), key=lambda s: s.start_time)


def _most_recent_preceding_llm(trace: list[Span], t: float) -> Optional[Span]:
    prior = [s for s in _llm_spans(trace) if s.end_time <= t + CLOCK_SKEW_SLACK]
    return prior[-1] if prior else None


def validate_causal_integrity(trace: list[Span]) -> None:
    by_id = {s.span_id: s for s in trace}
    llms = _llm_spans(trace)
    if not llms:
        return  # no reasoning spans; top-level tool invocation is legitimate

    for span in trace:
        if span.kind not in ("tool", "memory_read", "memory_write"):
            continue

        # Signal 1: edge completeness.
        parent = by_id.get(span.parent_span_id) if span.parent_span_id else None
        if parent is None or parent.kind != "llm":
            raise CausalDetachmentError(
                f"span {span.span_id} ({span.kind}) has no resolvable LLM parent "
                f"(parent_span_id={span.parent_span_id!r}); detached edge inside "
                f"trace {span.trace_id}"
            )

        # Signal 2: argument provenance.
        if span.kind == "tool" and span.payload not in parent.payload:
            raise CausalDetachmentError(
                f"span {span.span_id} executed with payload {span.payload!r} not "
                f"present in parent LLM span {parent.span_id} payload; edge is "
                f"misattributed to a different reasoning turn"
            )

        # Signal 3: turn ordinal for memory operations.
        if span.kind in ("memory_read", "memory_write"):
            recent = _most_recent_preceding_llm(trace, span.start_time)
            if recent is not None and recent.span_id != parent.span_id:
                raise CausalDetachmentError(
                    f"memory span {span.span_id} parented to {parent.span_id} but "
                    f"most recent preceding LLM span is {recent.span_id}; memory "
                    f"client captured a stale tracing context"
                )
