# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-replay-trace-s-causal-lineage-has-silently-re-rooted-after-a-checkpoint-restore.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-replay-trace-s-causal-lineage-has-silently-re-rooted-after-a-checkpoint-restore.warrant.json
# Markdown SHA-256:   40aaed61a70b55df086fd1b4f99af73be6bcf135e4c984a7e5ddaeb4e505a380
# Code AST SHA-256:   325a6862f870dcc0471b35cb8bf5ba9a1d44733e15813bfbf06170ca94d91e86
# Verified Classes:   LineageRerootError, Span, Handoff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class LineageRerootError(RuntimeError):
    """Raised when a span's DAG parent disagrees with its handoff witness."""


@dataclass(frozen=True)
class Span:
    span_id: str
    agent_instance_id: str
    parent_span_id: str | None
    is_synthetic_restore_root: bool = False


@dataclass(frozen=True)
class Handoff:
    delivering_span_id: str
    origin_span_id: str          # the span that produced the context
    origin_agent_instance_id: str


def verify_lineage(span: Span, handoff: Handoff, dag: dict[str, Span]) -> None:
    """Enforce: DAG parent must equal handoff origin, transitively to a real root."""
    if span.parent_span_id != handoff.origin_span_id:
        raise LineageRerootError(
            f"span {span.span_id} re-rooted: DAG parent={span.parent_span_id!r}, "
            f"handoff witness={handoff.origin_span_id!r} "
            f"(origin agent={handoff.origin_agent_instance_id})"
        )
    # Walk the parent closure; a synthetic restore-root mid-chain is a violation
    # unless the handoff explicitly acknowledges the restore boundary.
    cursor = span.parent_span_id
    while cursor is not None:
        node = dag.get(cursor)
        if node is None:
            raise LineageRerootError(
                f"span {span.span_id}: unresolvable parent {cursor!r} in DAG"
            )
        if node.is_synthetic_restore_root and cursor != handoff.origin_span_id:
            raise LineageRerootError(
                f"span {span.span_id}: synthetic restore-root {cursor!r} "
                f"interposed between span and true origin {handoff.origin_span_id!r}"
            )
        cursor = node.parent_span_id


def replay(dag: dict[str, Span], handoffs: list[Handoff]) -> None:
    for h in handoffs:
        span = dag[h.delivering_span_id]
        verify_lineage(span, h, dag)
