# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-genai-semantic-convention-spans-cross-an-agent-hop-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-genai-semantic-convention-spans-cross-an-agent-hop-boundary.warrant.json
# Markdown SHA-256:   8d1c655c88932517bf68304c161b3ff250121c2710ac85c5612492ab192d52e0
# Code AST SHA-256:   89a339396e3f53c50238492b9f5b4576628818a724e304fa0db72734947bedaa
# Verified Classes:   HopParentageError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class HopParentageError(RuntimeError):
    """Raised when a GenAI span at an agent hop boundary is re-rooted."""
    pass


def validate_hop_parentage(spans: list[dict], expected_parent_span_id: str) -> None:
    """Assert every gen_ai.agent.invoke span links to the caller's span.

    spans: exported span dicts with keys: name, span_id, parent_span_id, trace_id,
           attributes (gen_ai.conversation.id, gen_ai.agent.hop.parent_link_status)
    expected_parent_span_id: span_id of the caller's gen_ai.agent.invoke
    """
    for s in spans:
        if s["name"] != "gen_ai.agent.invoke":
            continue
        if s["parent_span_id"] in (None, "0000000000000000", ""):
            raise HopParentageError(
                f"re-rooted gen_ai.agent.invoke span {s['span_id']} "
                f"trace_id={s['trace_id']} has no parent; "
                f"expected parent={expected_parent_span_id}"
            )
        if s["parent_span_id"] != expected_parent_span_id:
            raise HopParentageError(
                f"mis-parented gen_ai.agent.invoke span {s['span_id']} "
                f"parent={s['parent_span_id']} expected={expected_parent_span_id} "
                f"conv_id={s['attributes'].get('gen_ai.conversation.id')}"
            )
        if s["attributes"].get("gen_ai.agent.hop.parent_link_status") == "rerooted":
            raise HopParentageError(
                f"hop reported rerooted status on span {s['span_id']}"
            )
