# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-parent-child-span-link-between-an-agent-s-prompt-span-and-its-downstream-retrieval-span.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-parent-child-span-link-between-an-agent-s-prompt-span-and-its-downstream-retrieval-span.warrant.json
# Markdown SHA-256:   7018740c6a5fc2f096c55c05c9c16571662ef1488378e37d9db998697f5d81d0
# Code AST SHA-256:   f70b56b7b34b63a25df2a8d11bd792065e135e7acc568db235cc430b3fe8a808
# Verified Classes:   TraceCorrelationError, Span, ToolCallRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceCorrelationError(RuntimeError):
    """Raised when a turn's prompt-to-retrieval span edges cannot be trusted."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    start_ns: int
    end_ns: int
    turn_id: Optional[str] = None


@dataclass(frozen=True)
class ToolCallRecord:
    """Agent-side ledger entry, written before the span is emitted."""
    turn_id: str
    intended_trace_id: str
    retrieval_span_id: str
    issued_at_ns: int


def verify_turn_correlation(
    prompt: Span,
    retrieval: Span,
    ledger: ToolCallRecord,
    trace_spans: list[Span],
    clock_skew_ns: int = 50_000_000,
) -> None:
    if prompt.turn_id != ledger.turn_id:
        raise TraceCorrelationError(
            f"prompt span turn {prompt.turn_id!r} != ledger turn {ledger.turn_id!r}"
        )

    # (a) trace identity must match both the prompt and the agent's intent.
    if retrieval.trace_id != prompt.trace_id:
        raise TraceCorrelationError(
            f"retrieval trace {retrieval.trace_id} != prompt trace {prompt.trace_id}; "
            "context was re-rooted downstream"
        )
    if retrieval.trace_id != ledger.intended_trace_id:
        raise TraceCorrelationError(
            f"retrieval trace {retrieval.trace_id} != intended {ledger.intended_trace_id}; "
            "context propagation diverged from agent intent"
        )

    # (b) retrieval must descend from the prompt within the same turn.
    ancestors = _ancestors(retrieval, trace_spans)
    if prompt.span_id not in ancestors:
        raise TraceCorrelationError(
            f"retrieval {retrieval.span_id} not descended from prompt {prompt.span_id}; "
            f"ancestors={sorted(ancestors)}"
        )

    # (c) timing must be causally consistent within clock skew.
    if retrieval.start_ns < prompt.start_ns - clock_skew_ns:
        raise TraceCorrelationError(
            f"retrieval {retrieval.span_id} starts before its prompt beyond skew; "
            "suspected fan-in mis-attribution"
        )

    # (d) no span ID may appear twice in the trace.
    seen: set[str] = set()
    for s in trace_spans:
        if s.trace_id != prompt.trace_id:
            continue
        if s.span_id in seen:
            raise TraceCorrelationError(
                f"duplicate span_id {s.span_id} in trace {s.trace_id}; "
                "attribution is undecidable under collision"
            )
        seen.add(s.span_id)


def _ancestors(span: Span, trace_spans: list[Span]) -> set[str]:
    by_id = {s.span_id: s for s in trace_spans if s.trace_id == span.trace_id}
    out: set[str] = set()
    cur = span.parent_span_id
    guard = 0
    while cur is not None:
        if cur in out or guard > len(by_id):
            raise TraceCorrelationError(f"cycle detected walking ancestors of {span.span_id}")
        out.add(cur)
        guard += 1
        parent = by_id.get(cur)
        cur = parent.parent_span_id if parent else None
    return out
