# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-severance-at-the-cross-org-span-boundary-in-federated-otel-genai-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-severance-at-the-cross-org-span-boundary-in-federated-otel-genai-agent-traces.warrant.json
# Markdown SHA-256:   e94465022264107a2f4d49b52af0f0364d551aeb1421c192c6e0f66cad9b03b3
# Code AST SHA-256:   96a7147bc741e9a268b3aec119075fe0c32f9974f2c2576133a5b3fd5c94942f
# Verified Classes:   TraceContextSeveranceError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

_TRACEPARENT = re.compile(
    r"^(?P<ver>[0-9a-f]{2})-(?P<trace>[0-9a-f]{32})-(?P<span>[0-9a-f]{16})-(?P<flags>[0-9a-f]{2})$"
)

class TraceContextSeveranceError(RuntimeError):
    """Raised when a cross-org span cannot honor the causal-continuity invariant."""

@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    agent_id: str
    parent_resolution: str  # "resolved" | "missing" | "promoted"

def ingest_cross_org_span(
    traceparent: str,
    tracestate: str | None,
    local_span_id: str,
    agent_id: str,
    known_span_ids: set[str],
    promote_to_root: bool,
) -> Span:
    m = _TRACEPARENT.match(traceparent or "")
    if not m:
        # Do NOT mint a fresh trace_id here; that is the unrecoverable severance.
        raise TraceContextSeveranceError(
            f"malformed traceparent {traceparent!r}: refusing to mint new trace_id"
        )

    trace_id, parent_span_id = m["trace"], m["span"]

    # tracestate is advisory: strip, never drop traceparent.
    if tracestate and len(tracestate.split(",")) > 32:
        tracestate = ",".join(tracestate.split(",")[:32])

    if parent_span_id in known_span_ids:
        return Span(trace_id, local_span_id, parent_span_id, agent_id, "resolved")

    # Parent is in another org's collector: unresolvable by construction.
    if promote_to_root:
        # Explicitly flagged promotion, not silent re-root.
        return Span(trace_id, local_span_id, None, agent_id, "promoted")
    return Span(trace_id, local_span_id, parent_span_id, agent_id, "missing")

def assert_continuity(spans: list[Span], expected_agent_chain: list[str]) -> None:
    by_agent = {s.agent_id: s for s in spans}
    for agent in expected_agent_chain:
        if agent not in by_agent:
            raise TraceContextSeveranceError(f"agent {agent} emitted no span")
        s = by_agent[agent]
        if s.parent_resolution == "promoted" and s.parent_span_id is None:
            # A promoted root must carry agent identity so rejoin is possible.
            if not s.agent_id:
                raise TraceContextSeveranceError(
                    f"span {s.span_id} promoted to root without agent.id; unrejoinable"
                )
    roots = [s for s in spans if s.parent_span_id is None]
    if len(roots) > 1 and not all(s.parent_resolution == "promoted" for s in roots):
        raise TraceContextSeveranceError(
            f"{len(roots)} roots under one trace_id with unflagged severance"
        )
