# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-parentage-when-a-multi-turn-agent-re-enters-a-suspended-tool-call-loop-after-context-compact.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-parentage-when-a-multi-turn-agent-re-enters-a-suspended-tool-call-loop-after-context-compact.warrant.json
# Markdown SHA-256:   191bc4a95b10d3b6a8547762cb78a4b57d4d3102d73cb694f8d81e4e7708e9f7
# Code AST SHA-256:   8cee1c515d526726edced5c3a14467a12c7e0f5cc9be1e8d8b8769e78f9db8ef
# Verified Classes:   SpanParentageViolation, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanParentageViolation(RuntimeError):
    """Raised when a resumed agent span cannot honor GenAI parentage invariants."""
    pass


@dataclass
class Checkpoint:
    traceparent: str
    parent_span_open: bool
    tokens_before: int
    tokens_after: int
    resume_paths: int


def emit_resumed_span(checkpoint: Checkpoint, span_kind: str) -> str:
    compacted = checkpoint.tokens_after < checkpoint.tokens_before
    # Invariant: direct re-parenting is valid ONLY for live, uncompacted,
    # single-path resumes. Anything else must route through a continuation span.
    if compacted and span_kind != "gen_ai.resume":
        raise SpanParentageViolation(
            f"cannot re-parent {span_kind} directly: context compacted "
            f"({checkpoint.tokens_before}->{checkpoint.tokens_after}); "
            f"emit gen_ai.resume continuation span first"
        )
    if not checkpoint.parent_span_open and span_kind != "gen_ai.resume":
        raise SpanParentageViolation(
            f"cannot attach {span_kind} to closed parent span; "
            f"re-base via gen_ai.resume"
        )
    if checkpoint.resume_paths > 1 and span_kind != "gen_ai.resume":
        raise SpanParentageViolation(
            f"duplicate resume ({checkpoint.resume_paths} paths) under one "
            f"parent; must disambiguate with gen_ai.resume spans"
        )
    # Valid: emit with persisted traceparent (or the continuation span itself).
    return f"emitted {span_kind} under {checkpoint.traceparent}"
