# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-fragmentation-at-agent-identity-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-fragmentation-at-agent-identity-boundaries.warrant.json
# Markdown SHA-256:   799078e624b63c4c88ce713060e0797fbb21b1cbf363b3afc8c04f9ad1697ec2
# Code AST SHA-256:   0536b98dbf71d8f868acc33b6142c1d4fbff4816c8cc7761feb3aa3029977d62
# Verified Classes:   TraceFragmentCollision, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from collections import defaultdict
from dataclasses import dataclass


class TraceFragmentCollision(RuntimeError):
    """Raised when a span_id appears under multiple trace_ids, indicating
    in-place traceparent mutation across an identity boundary."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    principal: str          # credential principal that emitted the span
    warrant_audience: str   # audience claim of the warrant authorizing the hop


def assert_span_id_uniqueness(spans: list[Span]) -> None:
    """Collector-side invariant: span_id must map to exactly one trace_id.

    Violation means a pre-export hook regenerated trace_id while preserving
    span_id -- the signature of in-place context mutation.
    """
    seen: dict[str, set[str]] = defaultdict(set)
    for s in spans:
        seen[s.span_id].add(s.trace_id)
    for span_id, trace_ids in seen.items():
        if len(trace_ids) > 1:
            raise TraceFragmentCollision(
                f"span_id {span_id!r} appears under trace_ids {sorted(trace_ids)}; "
                f"trace context was mutated in place across an identity boundary. "
                f"Use a Link to the inherited context instead of rewriting traceparent."
            )


def assert_principal_matches_warrant(spans: list[Span]) -> None:
    """Identity invariant: the emitting principal must match the warrant
    audience that authorized this hop. A mismatch means the span was emitted
    under a forwarded (not re-minted) warrant -- the root cause of the rewrite."""
    for s in spans:
        if s.principal != s.warrant_audience:
            raise TraceFragmentCollision(
                f"span {s.span_id!r} emitted by principal {s.principal!r} "
                f"under warrant audience {s.warrant_audience!r}; warrant was "
                f"forwarded verbatim rather than re-minted for this hop."
            )
