# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-spans-from-silently-truncating-an-agent-s-causal-trace-across-mcp-tool-calls-a2a-handoffs-and-memory-reads.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-spans-from-silently-truncating-an-agent-s-causal-trace-across-mcp-tool-calls-a2a-handoffs-and-memory-reads.warrant.json
# Markdown SHA-256:   39a39a5371b65a482b0c8062b740439428a3f1fdea289dd92b26d7e39860027a
# Code AST SHA-256:   e5d0ffb27f850fd07b509a537c42af6c34db4a5cfae6c175059ae60cc45fb3a0
# Verified Classes:   TraceDiscontinuity, Span, TraceBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

MAX_TRACESTATE_BYTES = 512


class TraceDiscontinuity(RuntimeError):
    """Raised when an exported span's parent is not co-present in its trace."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    is_root: bool = False
    name: str = ""


@dataclass
class TraceBuffer:
    spans: dict = field(default_factory=dict)  # span_id -> Span

    def add(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def validate(self, trace_id: str) -> None:
        members = [s for s in self.spans.values() if s.trace_id == trace_id]
        ids = {s.span_id for s in members}
        for s in members:
            if s.is_root:
                continue
            if s.parent_span_id is None or s.parent_span_id not in ids:
                raise TraceDiscontinuity(
                    f"span {s.span_id} ({s.name}) in trace {trace_id} "
                    f"references missing parent {s.parent_span_id}; "
                    f"causal chain is open at this hop"
                )


def truncate_tracestate(header: str) -> str:
    """Drop vendor entries from the right until under the W3C limit.

    Dropping the whole header (the observed bug) forces downstream
    re-sampling and orphans the child span. Truncating preserves the
    sampling decision carried by the root vendor entry.
    """
    if len(header.encode("utf-8")) <= MAX_TRACESTATE_BYTES:
        return header
    entries = header.split(",")
    while entries and len(",".join(entries).encode("utf-8")) > MAX_TRACESTATE_BYTES:
        entries.pop()
    if not entries:
        raise TraceDiscontinuity(
            "tracestate truncation removed all entries; refusing to drop "
            "sampling context wholesale"
        )
    return ",".join(entries)


def validate_export(buf: TraceBuffer, trace_id: str) -> None:
    buf.validate(trace_id)
