# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-context-grafting-from-silently-corrupting-parent-child-span-topology-across-federated-agent-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-context-grafting-from-silently-corrupting-parent-child-span-topology-across-federated-agent-boundaries.warrant.json
# Markdown SHA-256:   adad015a0df098a9934b602f2e73d740230f3bf4a77d5054fc154800f820816a
# Code AST SHA-256:   5d935f2eee997f42365739fd45cd04a7909bfc4112d6aa762f51db4c84238e77
# Verified Classes:   SpanTopologyError, SpanContext, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional


class SpanTopologyError(RuntimeError):
    """Raised when a span would violate cross-boundary parentage invariants."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    agent_id: str
    conversation_id: Optional[str] = None


@dataclass
class Span:
    trace_id: str
    span_id: str
    agent_id: str
    parent_span_id: Optional[str] = None
    links: list[SpanContext] = field(default_factory=list)
    ownership: set[str] = field(default_factory=set)


def adopt_inbound_context(
    local: Span,
    inbound: SpanContext,
    *,
    synchronous_containment: bool,
) -> Span:
    """
    Apply the cross-boundary invariant: only adopt a parent when the inbound
    context is owned by the same agent AND the call is synchronous containment.
    Otherwise downgrade to a link.
    """
    same_owner = inbound.agent_id == local.agent_id
    if synchronous_containment and same_owner:
        local.parent_span_id = inbound.span_id
        local.trace_id = inbound.trace_id
        return local

    # Cross-owner or async/delegated: association, not causality.
    if inbound.agent_id not in local.ownership:
        local.links.append(inbound)
        return local

    # Same owner, non-synchronous: still association, but flag it loudly.
    local.links.append(inbound)
    return local


def assert_topology(span: Span, resolved_parent: Optional[Span]) -> None:
    """Emit-time guard. Raises instead of silently exporting a corrupt edge."""
    if span.parent_span_id is None:
        return
    if resolved_parent is None:
        raise SpanTopologyError(
            f"span {span.span_id} references missing parent {span.parent_span_id}"
        )
    if resolved_parent.agent_id not in span.ownership:
        raise SpanTopologyError(
            f"span {span.span_id} (agent={span.agent_id}) claims parent "
            f"{resolved_parent.span_id} owned by {resolved_parent.agent_id} "
            f"outside its ownership set; downgrade to a link"
        )
    if resolved_parent.trace_id != span.trace_id:
        raise SpanTopologyError(
            f"span {span.span_id} parent {resolved_parent.span_id} "
            f"crosses trace_id {span.trace_id} != {resolved_parent.trace_id}"
        )
