# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-broken-causal-lineage-when-a-federated-trace-span-arrives-with-a-parent-pointer-that-resolves-to-a-memory-epoch-the-local.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-broken-causal-lineage-when-a-federated-trace-span-arrives-with-a-parent-pointer-that-resolves-to-a-memory-epoch-the-local.warrant.json
# Markdown SHA-256:   bd430b28e77bce2ab02b466fd7c5be1090be36bfb9ddc1865fddb6bfd98dc465
# Code AST SHA-256:   2ec71624fbed29bb49023d73e855c4fd544a5508338768ecf1c1281194f6c73a
# Verified Classes:   LineageStitchError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class LineageStitchError(RuntimeError):
    """Raised when a federated span's causal parent cannot be validated or uniquely repaired."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    agent_id: str
    memory_epoch: int
    observed_epochs: set[int] = field(default_factory=set)
    lineage_repaired: bool = False


def validate_and_stitch(child: Span, parent: Span, epoch_graph: dict[int, set[int]]) -> Span:
    # Clause 1: parent's epoch must be in child's observed set.
    if parent.memory_epoch not in child.observed_epochs:
        raise LineageStitchError(
            f"span {child.span_id} claims parent {parent.span_id} at epoch "
            f"{parent.memory_epoch}, but child never observed that epoch "
            f"(observed={sorted(child.observed_epochs)})"
        )

    # Clause 2: no divergent fork between parent epoch and child epoch.
    path = _epoch_path(parent.memory_epoch, child.memory_epoch, epoch_graph)
    if path is None:
        raise LineageStitchError(
            f"no epoch path from {parent.memory_epoch} to {child.memory_epoch} "
            f"for span {child.span_id}; lineage fork detected"
        )

    # Attempt unique repair only if the declared parent is the maximal observed epoch.
    candidates = [
        e for e in child.observed_epochs
        if e <= child.memory_epoch and e > parent.memory_epoch
    ]
    if len(candidates) > 1:
        raise LineageStitchError(
            f"ambiguous re-stitch for span {child.span_id}: multiple candidate "
            f"parent epochs {sorted(candidates)}; quarantine required"
        )
    if candidates:
        child.lineage_repaired = True
    return child


def _epoch_path(src: int, dst: int, graph: dict[int, set[int]]) -> list[int] | None:
    if src == dst:
        return [src]
    frontier, seen = [src], {src}
    while frontier:
        nxt = []
        for node in frontier:
            for succ in graph.get(node, set()):
                if succ == dst:
                    return [src, dst]
                if succ not in seen:
                    seen.add(succ)
                    nxt.append(succ)
        frontier = nxt
    return None
