# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-represent-a-tool-call-tree-when-the-genai-semantic-conventions-span-parent-child-model-collides-with-agent-reasoning-that-fans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-represent-a-tool-call-tree-when-the-genai-semantic-conventions-span-parent-child-model-collides-with-agent-reasoning-that-fans.warrant.json
# Markdown SHA-256:   26431dbba7ab6d7c20b1978cb1906a05506801a7d8e9b72f7df74b16719891ac
# Code AST SHA-256:   b594273d8504e98d0a37e26b3160c819f6c36d48dd657132abbb0ad1697c13da
# Verified Classes:   CausallyIncompleteTraceError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import dataclasses
from typing import Iterable


class CausallyIncompleteTraceError(RuntimeError):
    """Raised when a rejoin span's consumed tool spans are not reachable
    from it via parent edges (through a join node) or explicit links.
    The trace would be schema-valid but causally false."""


@dataclasses.dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    links: tuple[str, ...] = ()


def _ancestors(span: Span, by_id: dict[str, Span]) -> set[str]:
    seen: set[str] = set()
    cur = span.parent_id
    while cur is not None and cur not in seen:
        seen.add(cur)
        cur = by_id[cur].parent_id if cur in by_id else None
    return seen


def assert_rejoin_reachable(
    rejoin: Span,
    consumed: Iterable[Span],
    all_spans: Iterable[Span],
) -> None:
    """Invariant: every consumed tool span must be a link of the rejoin span
    OR an ancestor of it (which holds when a synthetic join node parents both
    the tools and the rejoin span)."""
    by_id = {s.span_id: s for s in all_spans}
    ancestors = _ancestors(rejoin, by_id)
    linked = set(rejoin.links)

    orphaned = [
        t.span_id
        for t in consumed
        if t.span_id not in ancestors and t.span_id not in linked
    ]
    if orphaned:
        raise CausallyIncompleteTraceError(
            f"rejoin span {rejoin.span_id!r} consumes {orphaned!r} but reaches "
            f"them via neither a join-node ancestor nor a span link; trace is "
            f"schema-valid and causally false. Insert a synthetic join span or "
            f"attach follows_from links before closing the rejoin span."
        )
