# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-trace-parentage-when-a-federated-agent-hop-rewrites-its-span-context-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-trace-parentage-when-a-federated-agent-hop-rewrites-its-span-context-mid-execution.warrant.json
# Markdown SHA-256:   f7ce712f23be682b0bbf718e85954a6fd46ffe6f9f1be1a15e11aa2be3c6c5d4
# Code AST SHA-256:   ce9011cccf51e91174bb262c870010b59f16f9e84431c050a159b43d08da2167
# Verified Classes:   TraceParentageViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict
from typing import Optional


class TraceParentageViolation(RuntimeError):
    """Raised when a federated hop re-roots a span, breaking the parent-child invariant."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    runtime: str
    start_ns: int
    end_ns: int
    attributes: dict = field(default_factory=dict)


def audit_trace_integrity(spans: list[Span], *, allow_async_roots: bool = True) -> dict:
    """
    Enforce: every trace_id has exactly one root UNLESS roots are marked async
    (span link semantics). Non-root spans must have a parent present in the trace.
    """
    by_trace: dict[str, list[Span]] = defaultdict(list)
    for s in spans:
        by_trace[s.trace_id].append(s)

    report = {}
    for trace_id, group in by_trace.items():
        ids = {s.span_id for s in group}
        roots = [s for s in group if s.parent_span_id is None]
        orphans = [
            s for s in group
            if s.parent_span_id is not None and s.parent_span_id not in ids
        ]
        async_roots = [r for r in roots if r.attributes.get("link.semantics") == "async"]
        sync_roots = [r for r in roots if r not in async_roots]

        report[trace_id] = {
            "span_count": len(group),
            "root_count": len(roots),
            "sync_roots": len(sync_roots),
            "async_roots": len(async_roots),
            "orphans": [o.span_id for o in orphans],
            "runtimes": sorted({s.runtime for s in group}),
        }

        if orphans:
            raise TraceParentageViolation(
                f"trace {trace_id}: {len(orphans)} span(s) reference a parent "
                f"absent from the trace (dropped or re-rooted upstream): "
                f"{[o.span_id for o in orphans]}"
            )
        if len(sync_roots) > 1:
            raise TraceParentageViolation(
                f"trace {trace_id}: {len(sync_roots)} synchronous roots detected "
                f"across runtimes {report[trace_id]['runtimes']}; a federated hop "
                f"re-rooted its span (propagator dropped or extraction bypassed). "
                f"Roots: {[r.span_id for r in sync_roots]}"
            )
        if len(roots) > 1 and not allow_async_roots:
            raise TraceParentageViolation(
                f"trace {trace_id}: multiple roots but async links disallowed by policy"
            )
    return report


def propagate_hop(upstream: Span, downstream_runtime: str, *, synchronous: bool,
                  start_ns: int, end_ns: int, new_span_id: str) -> Span:
    """
    Build the downstream span. Synchronous hops MUST carry upstream.span_id as parent.
    Async hops emit a root but tag link semantics so the auditor tolerates it.
    """
    if synchronous:
        if not upstream.span_id:
            raise TraceParentageViolation(
                f"cannot propagate sync hop to {downstream_runtime}: "
                f"upstream span has no span_id (extraction failed upstream)"
            )
        return Span(
            trace_id=upstream.trace_id,
            span_id=new_span_id,
            parent_span_id=upstream.span_id,
            runtime=downstream_runtime,
            start_ns=start_ns,
            end_ns=end_ns,
        )
    # async: root, but explicitly linked back via attribute envelope
    return Span(
        trace_id=upstream.trace_id,
        span_id=new_span_id,
        parent_span_id=None,
        runtime=downstream_runtime,
        start_ns=start_ns,
        end_ns=end_ns,
        attributes={"link.semantics": "async",
                    "link.upstream_span_id": upstream.span_id},
    )
