# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-context-divergence-when-a-federated-a2a-hop-silently-re-parents-a-span.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-context-divergence-when-a-federated-a2a-hop-silently-re-parents-a-span.warrant.json
# Markdown SHA-256:   045a9759a20daf6b54ad2855320e6737aac146f51a06a040ecc8bbc25583e0f2
# Code AST SHA-256:   5321fc6b207a6a2a1b6dea7dcca144c114aae27269493159b01e4aa5be1437ba
# Verified Classes:   TraceDivergenceError, EmitRecord, ObservedSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceDivergenceError(RuntimeError):
    """Raised when a federated A2A hop's emitted span tree does not honor the sent parent."""
    pass


@dataclass(frozen=True)
class EmitRecord:
    task_id: str
    trace_id: str
    sent_span_id: str          # span_id X placed in outbound traceparent
    next_hop_parent_id: str    # span_id X's successor recorded as parent to next hop (if any)


@dataclass(frozen=True)
class ObservedSpan:
    span_id: str
    parent_span_id: str | None
    trace_id: str


def assert_hop_continuity(
    record: EmitRecord,
    observed: list[ObservedSpan],
    next_hop_parent_id: str | None,
) -> None:
    """Verify the sent-parent is an ancestor of the next-hop parent.

    Raises TraceDivergenceError on silent re-parenting. Does not attempt repair.
    """
    by_id = {s.span_id: s for s in observed if s.trace_id == record.trace_id}

    children_of_sent = [s for s in by_id.values() if s.parent_span_id == record.sent_span_id]
    if not children_of_sent:
        # Visible orphan: sent-parent has no children at all.
        raise TraceDivergenceError(
            f"task {record.task_id}: sent-parent {record.sent_span_id} has no children; "
            f"context lost, not re-parented"
        )

    if next_hop_parent_id is None:
        return  # terminal hop; multiplicity tolerated

    # Walk up from next-hop parent to see if any child_of_sent is an ancestor.
    cursor = by_id.get(next_hop_parent_id)
    seen: set[str] = set()
    while cursor is not None and cursor.span_id not in seen:
        seen.add(cursor.span_id)
        if cursor.span_id in {c.span_id for c in children_of_sent}:
            return
        cursor = by_id.get(cursor.parent_span_id) if cursor.parent_span_id else None

    raise TraceDivergenceError(
        f"task {record.task_id}: next-hop parent {next_hop_parent_id} does not descend from "
        f"any child of sent-parent {record.sent_span_id}; silent re-parenting detected "
        f"(children={[c.span_id for c in children_of_sent]})"
    )
