# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-divergence-when-delegating-agents-cross-organizational-boundaries-under-otel-genai-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-divergence-when-delegating-agents-cross-organizational-boundaries-under-otel-genai-semantics.warrant.json
# Markdown SHA-256:   9f1fc5aa80e33e3c939b31d190b052aadeec0856ab7c46f7874caf4b8a561306
# Code AST SHA-256:   a01a14a436050be10c8940e548c02a5574a21d56e7d3e0ae318354ab290a1a0f
# Verified Classes:   DelegationTraceIntegrityError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationTraceIntegrityError(RuntimeError):
    """Raised when a cross-org delegation edge satisfies syntactic trace
    continuity but violates the semantic delegation invariant."""
    pass


@dataclass
class Span:
    trace_id: str
    parent_span_id: str | None
    span_id: str
    delegation_depth: int
    conversation_id: str
    warrant_ref: str | None
    sampled: bool


def admit_delegation_edge(
    parent: Span,
    child: Span,
    *,
    conversation_authority: str,
    verify_warrant,
) -> None:
    # (a) syntactic continuity
    if child.trace_id != parent.trace_id:
        raise DelegationTraceIntegrityError(
            f"propagation loss: trace_id mismatch "
            f"{parent.trace_id!r} != {child.trace_id!r}"
        )
    if child.parent_span_id != parent.span_id:
        raise DelegationTraceIntegrityError(
            f"parent_span_id {child.parent_span_id!r} does not link to {parent.span_id!r}"
        )

    # (b) depth monotonicity — the silent-corruption detector
    if child.delegation_depth != parent.delegation_depth + 1:
        raise DelegationTraceIntegrityError(
            f"delegation depth non-monotonic: parent={parent.delegation_depth} "
            f"child={child.delegation_depth} (tracestate truncation suspected)"
        )

    # (c) warrant lineage must verify, not merely be present
    if child.warrant_ref is None or not verify_warrant(child.warrant_ref):
        raise DelegationTraceIntegrityError(
            f"delegation-unverified: warrant_ref={child.warrant_ref!r} "
            f"failed verification for span {child.span_id}"
        )

    # (d) single conversation authority
    if child.conversation_id != conversation_authority:
        raise DelegationTraceIntegrityError(
            f"conversation-ID authority violation: {child.conversation_id!r} "
            f"!= authority {conversation_authority!r} (collision risk)"
        )

    # (e) sampling must be propagated, not re-decided
    if parent.sampled and not child.sampled:
        raise DelegationTraceIntegrityError(
            f"sampling-flag asymmetry: parent sampled, child {child.span_id} dropped"
        )
