# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-span-orphaning-in-opentelemetry-genai-traces-when-multi-agent-handoffs-cross-context-window-compaction-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-span-orphaning-in-opentelemetry-genai-traces-when-multi-agent-handoffs-cross-context-window-compaction-boundaries.warrant.json
# Markdown SHA-256:   9ec1d017a4dbdf3bf27bfbf1f80239a3d1385f3fa8eba73086e456ad20867196
# Code AST SHA-256:   47fcb5799895684cfa9b8d8ff376d8305cf4e62f5646fa6d596fbb1d638a7f05
# Verified Classes:   CausalLinkSeveredError, DelegationPayload
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

NON_SUMMARIZABLE = frozenset({
    "traceparent", "tracestate", "delegation_id", "parent_span_context",
})


class CausalLinkSeveredError(RuntimeError):
    """Raised when a delegation boundary would orphan a child span from its causal parent."""


@dataclass
class DelegationPayload:
    delegation_id: str
    parent_span_context: Optional[str]  # serialized W3C traceparent
    body: dict


def compact_transcript(turns: list[dict]) -> list[dict]:
    """Summarizer that must never drop causal-link metadata."""
    kept = []
    for turn in turns:
        for key in turn:
            if key.lower() in NON_SUMMARIZABLE:
                raise CausalLinkSeveredError(
                    f"compactor attempted to summarize non-summarizable field {key!r}; "
                    "causal link to parent span would be severed"
                )
        kept.append(turn)
    return kept


def child_bootstrap(payload: DelegationPayload) -> str:
    """Child runtime must fail closed if a delegation arrived without a parent context."""
    if payload.delegation_id and not payload.parent_span_context:
        raise CausalLinkSeveredError(
            f"delegation {payload.delegation_id} arrived without parent_span_context; "
            "refusing to start a root span (would orphan child trace)"
        )
    if payload.parent_span_context and not payload.parent_span_context.startswith("00-"):
        raise CausalLinkSeveredError(
            f"malformed traceparent {payload.parent_span_context!r} for delegation "
            f"{payload.delegation_id}"
        )
    return payload.parent_span_context or ""


def assert_delegation_has_child(spans: list[dict]) -> None:
    """Export-time invariant: every delegation span has exactly one child in the same trace."""
    by_parent: dict[str, list[str]] = {}
    for s in spans:
        if s.get("parent_span_id"):
            by_parent.setdefault(s["parent_span_id"], []).append(s["span_id"])
    for s in spans:
        if s.get("name") == "gen_ai.delegation":
            children = by_parent.get(s["span_id"], [])
            if len(children) != 1:
                raise CausalLinkSeveredError(
                    f"delegation span {s['span_id']} has {len(children)} children "
                    f"(expected 1); causal edge to child agent is severed"
                )
