# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-correlation-id-orphanage-in-cross-hop-agent-trace-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-correlation-id-orphanage-in-cross-hop-agent-trace-reconstruction.warrant.json
# Markdown SHA-256:   d5a4ce663d01e1d8d379d84e9c5efaa9949e6dd533d2037f0c897b24b9c1be9e
# Code AST SHA-256:   8a6d3ccda96a88cddd2458e8e8279d5287469f1477ab3b1889ff33ddcc375b1d
# Verified Classes:   CorrelationIdOrphanageError, HopContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

_UUID_RE = re.compile(
    r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
)


class CorrelationIdOrphanageError(RuntimeError):
    """Raised when a hop's emitted correlation ID diverges from its ingress copy."""


@dataclass(frozen=True)
class HopContext:
    ingress_correlation_id: str   # retained verbatim from transport, never model-generated
    emitted_correlation_id: str   # what the child is about to put on its span


def assert_byte_equal_propagation(ctx: HopContext) -> None:
    """Invariant: emitted ID must be byte-identical to the retained ingress copy.

    Format-validity alone is insufficient: a truncated or normalized ID is
    still format-valid but forks the trace silently.
    """
    ingress = ctx.ingress_correlation_id
    emitted = ctx.emitted_correlation_id

    if not _UUID_RE.match(ingress):
        raise CorrelationIdOrphanageError(
            f"ingress correlation id malformed at source: {ingress!r}"
        )

    if emitted != ingress:
        # Classify the divergence for the operator before raising.
        if emitted and ingress.startswith(emitted):
            kind = "truncation"
        elif emitted and emitted.lower() == ingress.lower():
            kind = "case-normalization"
        elif emitted and emitted.replace("-", "") == ingress.replace("-", ""):
            kind = "separator-normalization"
        else:
            kind = "stale-or-foreign-id"
        raise CorrelationIdOrphanageError(
            f"correlation id orphanage ({kind}): "
            f"ingress={ingress!r} emitted={emitted!r}"
        )


def emit_child_span(ctx: HopContext) -> str:
    assert_byte_equal_propagation(ctx)
    return ctx.emitted_correlation_id
