# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-propagate-a-traceparent-across-an-organizational-boundary-the-privacy-spanning-join-hazard-in-federated-agent-observab.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-propagate-a-traceparent-across-an-organizational-boundary-the-privacy-spanning-join-hazard-in-federated-agent-observab.warrant.json
# Markdown SHA-256:   9463221b82d4decc4c24edc6ca30e482080615148afa23888b1ae70fdc578ab2
# Code AST SHA-256:   3419c70d2f236c09409176adbe3916088de76421a341f958576824f180eeef72
# Verified Classes:   TrustDomain, UnlicensedCrossDomainJoin, ClosedParentViolation, Span, ExportPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TrustDomain(str, Enum):
    ORG_A = "org-a"
    ORG_B = "org-b"


class UnlicensedCrossDomainJoin(RuntimeError):
    """Raised when a span would create a join edge across a trust boundary
    without an enumerated, consented basis for that join."""


class ClosedParentViolation(RuntimeError):
    """Raised when a retry span points at a parent already closed on the
    receiving side, which would fork the trace into a second timeline."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    origin_domain: TrustDomain
    attributes: dict = field(default_factory=dict)
    # True if the receiving side can resolve this trace to a natural person.
    identity_resolvable_at_receiver: bool = False


@dataclass(frozen=True)
class ExportPolicy:
    destination: TrustDomain
    # Enumerated join licenses, keyed by (origin, destination). Empty = no join.
    licensed_joins: frozenset = frozenset()
    # Attributes that are sensitive-when-attributed; must be coarsened or absent.
    sensitive_when_attributed: frozenset = frozenset(
        {"tool.name", "gen_ai.agent.name", "enduser.id", "net.peer.ip"}
    )


def gate_egress(span: Span, policy: ExportPolicy) -> Span:
    """Return a span safe to export, or raise. Never returns a span that
    carries an unlicensed cross-domain join edge."""
    cross_domain = span.origin_domain != policy.destination

    if not cross_domain:
        return span

    join = (span.origin_domain, policy.destination)
    if join not in policy.licensed_joins:
        # The trace ID is a foreign key to the receiver's identity graph.
        # Scrubbing attributes does not remove the edge; we must terminate it.
        raise UnlicensedCrossDomainJoin(
            f"refusing to export trace {span.trace_id!r} from "
            f"{span.origin_domain.value} to {policy.destination.value}: "
            f"no licensed join {join!r}. Terminate the trace (mint a fresh "
            f"trace_id and keep the original in a local linkage table) instead "
            f"of scrubbing attributes."
        )

    if span.identity_resolvable_at_receiver:
        leaked = set(span.attributes) & policy.sensitive_when_attributed
        if leaked:
            raise UnlicensedCrossDomainJoin(
                f"licensed join {join!r} permits propagation, but span "
                f"{span.span_id!r} carries {sorted(leaked)!r}, which is "
                f"sensitive when attributed to a resolvable identity. "
                f"Coarsen these attributes before egress."
            )

    return span


def accept_span(span: Span, closed_span_ids: set[str]) -> Span:
    """Receiving-side guard against retry-forked traces."""
    if span.parent_span_id is not None and span.parent_span_id in closed_span_ids:
        raise ClosedParentViolation(
            f"span {span.span_id!r} references parent {span.parent_span_id!r} "
            f"which is already closed on this side; accepting it would fork "
            f"trace {span.trace_id!r} into a second timeline. The retry must "
            f"re-parent to the logical operation, not the failed attempt."
        )
    return span


def terminate_trace(span: Span, new_trace_id: str) -> Span:
    """Boundary-terminating rewrite: fresh trace_id, original kept locally."""
    return Span(
        trace_id=new_trace_id,
        span_id=span.span_id,
        parent_span_id=None,
        origin_domain=span.origin_domain,
        attributes=dict(span.attributes),
        identity_resolvable_at_receiver=False,
    )
