# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-trace-correlation-semantics-across-mcp-tool-hops-and-a2a-agent-hops-without-silent-lineage-fracture.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-trace-correlation-semantics-across-mcp-tool-hops-and-a2a-agent-hops-without-silent-lineage-fracture.warrant.json
# Markdown SHA-256:   8d2ea8ebbbcb1aaf56acf0e9c90f84056ed9fb676600fbf5977196d822dde16f
# Code AST SHA-256:   cf023dac2c4734e04cb9e24aa3a977676b90ea1c8525096f8a9e83c49a8ec993
# Verified Classes:   TraceCorrelationFracture, Span
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceCorrelationFracture(RuntimeError):
    """Raised when a trace is linked by ID but hops disagree on semantic convention."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    convention_version: Optional[str]
    operation: str                      # e.g. "mcp.tools/call", "a2a.tasks/send"
    status_code: Optional[str]          # "OK" | "ERROR" | None
    error_type: Optional[str]           # MCP error taxonomy, may be None at A2A hop
    task_state: Optional[str]           # A2A task state, may be None at MCP hop
    attributes: dict = field(default_factory=dict)


def correlate(spans: list[Span]) -> dict:
    """Join spans into a composite verdict, refusing to guess across convention drift."""
    if not spans:
        raise TraceCorrelationFracture("no spans to correlate")

    trace_ids = {s.trace_id for s in spans}
    if len(trace_ids) != 1:
        raise TraceCorrelationFracture(
            f"spans span multiple trace_ids: {trace_ids}"
        )

    # 1. Convention version must be present and identical on every span.
    versions = {s.convention_version for s in spans}
    if None in versions:
        raise TraceCorrelationFracture(
            "at least one span omits convention.version; join is unverified"
        )
    if len(versions) != 1:
        raise TraceCorrelationFracture(
            f"convention version drift across hops: {versions}"
        )

    # 2. Error-to-status mapping must be invertible: an MCP ERROR must be
    #    representable as an A2A failed state, and vice versa, or a sidecar
    #    attribute must preserve the original taxonomy.
    for s in spans:
        if s.status_code == "ERROR" and s.error_type is None:
            raise TraceCorrelationFracture(
                f"span {s.span_id} reports ERROR with no error_type; "
                "error taxonomy lost at hop boundary"
            )
        if s.task_state == "failed" and s.error_type is None and \
                "a2a.error.type" not in s.attributes:
            raise TraceCorrelationFracture(
                f"span {s.span_id} reports A2A failed with no preserved "
                "error taxonomy; verdict would be lossy"
            )

    # 3. Parent edges must be verified, not inferred from adjacency.
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.parent_span_id is not None and s.parent_span_id not in by_id:
            raise TraceCorrelationFracture(
                f"span {s.span_id} references missing parent "
                f"{s.parent_span_id}; causal edge unverifiable"
            )

    # 4. Derive verdict only after all preconditions hold.
    failed = any(
        s.status_code == "ERROR" or s.task_state == "failed" for s in spans
    )
    return {
        "trace_id": next(iter(trace_ids)),
        "convention_version": next(iter(versions)),
        "verdict": "failure" if failed else "success",
        "span_count": len(spans),
    }


def emit_composite_verdict(spans: list[Span]) -> dict:
    try:
        return correlate(spans)
    except TraceCorrelationFracture as exc:
        # Fail closed: surface the fracture as a first-class outcome rather
        # than emitting a guessed verdict downstream.
        raise TraceCorrelationFracture(
            f"refusing to emit composite verdict: {exc}"
        ) from exc
