# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-causal-span-linkage-when-a-tool-call-graph-re-enters-a-prior-decision-node.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-causal-span-linkage-when-a-tool-call-graph-re-enters-a-prior-decision-node.warrant.json
# Markdown SHA-256:   4f950deff59ccaa952fac9476aaead0c019cd129d8c0080eff3716e0c7bca612
# Code AST SHA-256:   ddfbd3dea883e34ce3b75ba32becd6fb8cd62341fde04018a880721c7dedbd90
# Verified Classes:   CausalLinkIntegrityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CausalLinkIntegrityError(RuntimeError):
    """Raised when a GenAI span's recorded causal inputs do not form a valid DAG edge set."""
    pass


def validate_span(span: dict, known_spans: dict[str, dict]) -> None:
    span_id = span["span_id"]
    parent = span.get("parent_span_id")
    causal = span.get("causal_inputs")

    if causal is None:
        raise CausalLinkIntegrityError(
            f"span {span_id}: causal_inputs not emitted before prompt eviction; "
            f"causal edge set is unrecoverable"
        )

    if parent is not None and parent not in causal:
        # temporal parent must be a causal input, else the spine and DAG disagree
        raise CausalLinkIntegrityError(
            f"span {span_id}: parent {parent} absent from causal_inputs {sorted(causal)}; "
            f"graph would be rewritten as a tree and lose re-entry"
        )

    for src in causal:
        if src == span_id:
            raise CausalLinkIntegrityError(f"span {span_id}: self-edge in causal_inputs")
        if src not in known_spans:
            raise CausalLinkIntegrityError(
                f"span {span_id}: causal input {src} references unknown span"
            )
        # re-entry detection: a causal input that is not an ancestor is the exact
        # condition single-parent linking erases
        if src != parent and not _is_ancestor(src, parent, known_spans):
            span.setdefault("reentry_edges", []).append(src)


def _is_ancestor(candidate: str, node: str | None, known: dict[str, dict]) -> bool:
    seen = set()
    while node is not None and node not in seen:
        if node == candidate:
            return True
        seen.add(node)
        node = known[node].get("parent_span_id")
    return False


def build_causal_graph(spans: list[dict]) -> dict[str, list[str]]:
    known = {s["span_id"]: s for s in spans}
    for s in spans:
        validate_span(s, known)
    return {s["span_id"]: sorted(s["causal_inputs"]) for s in spans}
