# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-decoherence-at-mcp-transport-boundaries-orphaned-span-parents-and-the-correlation-identity-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-decoherence-at-mcp-transport-boundaries-orphaned-span-parents-and-the-correlation-identity-invariant.warrant.json
# Markdown SHA-256:   d86baf5f826ec05db61a034c7ca24ebb19246bb499bb973e59975b095c3b234b
# Code AST SHA-256:   5f445fbc465d1dd58db2fbede2682528bed891802825a6e94ae76fde6c5bf34b
# Verified Classes:   TraceCorrelationError, Span, TraceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TraceCorrelationError(RuntimeError):
    """Raised when a span cannot be resolved to a unique parent within its trace."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    hop: int
    name: str


@dataclass
class TraceStore:
    spans: dict[str, dict[str, list[Span]]] = field(default_factory=dict)

    def add(self, span: Span) -> None:
        self.spans.setdefault(span.trace_id, {}).setdefault(span.span_id, []).append(span)

    def resolve(self, trace_id: str, span_id: str) -> Span:
        candidates = self.spans.get(trace_id, {}).get(span_id, [])
        if not candidates:
            raise TraceCorrelationError(
                f"parent {span_id} not exported under trace {trace_id}"
            )
        if len({c.parent_span_id for c in candidates}) > 1:
            raise TraceCorrelationError(
                f"ambiguous parent: span {span_id} in trace {trace_id} "
                f"has {len(candidates)} instances with divergent parents "
                f"({[c.parent_span_id for c in candidates]})"
            )
        return candidates[0]

    def orphan_rate_by_hop(self) -> dict[int, float]:
        totals: dict[int, int] = {}
        orphans: dict[int, int] = {}
        for trace_id, by_id in self.spans.items():
            for span_id, instances in by_id.items():
                for s in instances:
                    totals[s.hop] = totals.get(s.hop, 0) + 1
                    if s.parent_span_id is None:
                        continue
                    try:
                        self.resolve(trace_id, s.parent_span_id)
                    except TraceCorrelationError:
                        orphans[s.hop] = orphans.get(s.hop, 0) + 1
        return {h: orphans.get(h, 0) / totals[h] for h in totals}


def assert_correlation_invariant(store: TraceStore, hop: int) -> None:
    rates = store.orphan_rate_by_hop()
    base = rates.get(1, 0.0)
    current = rates.get(hop, 0.0)
    # Guardrail: alert on derivative w.r.t. hop depth, not absolute level.
    if current - base > 0.10:
        raise TraceCorrelationError(
            f"orphan rate jumped from {base:.2%} at hop 1 to {current:.2%} at hop {hop}; "
            f"transport-boundary propagation is lossy — trace is not authoritative "
            f"for cross-hop causality"
        )


def mint_attempt_span(trace_id: str, parent_span_id: str, attempt: int) -> Span:
    # Attempt-unique span id: prevents retry from reusing a parent-bearing id.
    digest = hashlib.sha256(f"{trace_id}:{parent_span_id}:{attempt}".encode()).hexdigest()[:16]
    return Span(trace_id=trace_id, span_id=digest, parent_span_id=parent_span_id,
                hop=2, name="mcp.tools.call")


if __name__ == "__main__":
    store = TraceStore()
    root = Span("t-1", "root0", None, hop=1, name="agent.turn")
    store.add(root)
    # Hop-2 span whose transport shim dropped _meta: parent is not exported.
    store.add(Span("t-1", "srv1", "missing-parent", hop=2, name="memory.write"))
    assert_correlation_invariant(store, hop=2)  # raises TraceCorrelationError
