# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-causal-fragments-when-a-federated-trace-stitch-loses-its-parent-span-across-an-a2a-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-causal-fragments-when-a-federated-trace-stitch-loses-its-parent-span-across-an-a2a-hop.warrant.json
# Markdown SHA-256:   d1d56554131f50313d4affa7f105da52ef59112667bdfa330411163f8bcb25bf
# Code AST SHA-256:   7befba0c45a4f1ebd0af38a5d85329e88fd2e2f4f995915ec81dd1a8b0f0306b
# Verified Classes:   OrphanedCausalFragmentError, Span, StitchedTrace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedCausalFragmentError(RuntimeError):
    """Raised when a stitched trace cannot prove a span's true causal parent."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    task_id: str
    start_ns: int
    end_ns: int


@dataclass
class StitchedTrace:
    spans: list[Span] = field(default_factory=list)

    def roots(self) -> list[Span]:
        return [s for s in self.spans if s.parent_span_id is None]

    def overlaps(self, a: Span, b: Span) -> bool:
        return a.start_ns < b.end_ns and b.start_ns < a.end_ns


def certify_causal_chain(trace: StitchedTrace, expected_task_id: str) -> None:
    roots = [r for r in trace.roots() if r.task_id == expected_task_id]
    if len(roots) == 1:
        return  # single logical root: stitch certified

    if len(roots) > 1:
        # Multiple roots for one logical execution: an A2A hop re-rooted the trace.
        for i, a in enumerate(roots):
            for b in roots[i + 1:]:
                if trace.overlaps(a, b):
                    raise OrphanedCausalFragmentError(
                        f"Logical execution {expected_task_id!r} has {len(roots)} "
                        f"overlapping roots ({a.trace_id}, {b.trace_id}); "
                        f"causal parent of {b.span_id} is unproven. "
                        f"Reconcile via transport log before certifying."
                    )
        # Non-overlapping extra roots may be legitimate declared forks; still flag.
        raise OrphanedCausalFragmentError(
            f"Logical execution {expected_task_id!r} has {len(roots)} roots with "
            f"no declared causal-boundary record; refusing to certify."
        )

    raise OrphanedCausalFragmentError(
        f"No root span found for logical execution {expected_task_id!r}; "
        f"chain is broken at an inbound hop."
    )
