# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-the-traceparent-header-it-inherited.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-the-traceparent-header-it-inherited.warrant.json
# Markdown SHA-256:   0bab04fa0801b92a0fba5976012eddb874cc43daa6b4ed32a2675dad5a8d12f1
# Code AST SHA-256:   49290f23a7f8cd284b203267d7356615a27ca58a0f648b586a28b914441edbfb
# Verified Classes:   TraceContinuityError, TraceContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

TRACEPARENT_RE = re.compile(
    r"^(?P<version>[0-9a-f]{2})-(?P<trace_id>[0-9a-f]{32})-"
    r"(?P<parent_id>[0-9a-f]{16})-(?P<flags>[0-9a-f]{2})$"
)


class TraceContinuityError(RuntimeError):
    """Raised when an agent's outbound span severs the inherited trace."""


@dataclass(frozen=True)
class TraceContext:
    trace_id: str
    parent_id: str
    flags: str
    tracestate: tuple[str, ...] = ()

    @classmethod
    def parse(cls, header: str, tracestate: str = "") -> "TraceContext":
        m = TRACEPARENT_RE.match(header.strip())
        if not m:
            raise TraceContinuityError(f"malformed traceparent: {header!r}")
        entries = tuple(e.strip() for e in tracestate.split(",") if e.strip())
        return cls(m["trace_id"], m["parent_id"], m["flags"], entries)


def enforce_continuity(
    inherited: TraceContext, emitted_header: str, emitted_tracestate: str = ""
) -> TraceContext:
    """
    Gate applied at the receiving agent's ingress. The sender (an LLM instance)
    may have regenerated the traceparent during a compaction step; we do not
    trust it. We require trace-id equality and preservation of foreign
    tracestate entries.
    """
    emitted = TraceContext.parse(emitted_header, emitted_tracestate)

    if emitted.trace_id != inherited.trace_id:
        raise TraceContinuityError(
            "trace-id severed: inherited "
            f"{inherited.trace_id} but emitted {emitted.trace_id}. "
            "Sender regenerated the context instead of forwarding it."
        )

    if emitted.parent_id == inherited.parent_id:
        raise TraceContinuityError(
            f"parent-id not advanced: {emitted.parent_id}. "
            "A new span-id must be minted per hop."
        )

    inherited_vendors = {e.split("=", 1)[0] for e in inherited.tracestate}
    emitted_vendors = {e.split("=", 1)[0] for e in emitted.tracestate}
    dropped = inherited_vendors - emitted_vendors
    if dropped:
        raise TraceContinuityError(
            f"tracestate entries silently dropped: {sorted(dropped)}. "
            "Foreign vendor entries must be preserved and prepended to."
        )

    return emitted
