# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-trace-parent-identity-before-a-multi-hop-agent-chain-can-be-observably-continuous.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-trace-parent-identity-before-a-multi-hop-agent-chain-can-be-observably-continuous.warrant.json
# Markdown SHA-256:   5fa96055d8b5b1ab47e20b426421a421a492475aaf4959066841395041f90ed6
# Code AST SHA-256:   9a035e9c5ef5422892960cdd90f6e7cafcf889441135a3057923d7ae1430cac1
# Verified Classes:   TraceParentDivergence, ChainContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceParentDivergence(RuntimeError):
    """Raised when a non-root hop cannot resolve a valid parent span
    and would otherwise silently mint a new trace, severing the chain."""


@dataclass(frozen=True)
class ChainContext:
    trace_id: str
    parent_span_id: str
    role: str  # "root" | "downstream"


def resolve_parent_for_hop(
    inbound: Optional[ChainContext],
    hop_name: str,
    declared_root: bool = False,
) -> ChainContext:
    """
    Enforce the continuity invariant: a hop may only mint a trace_id if it
    is a declared root. Downstream hops must inherit or fail closed.
    """
    if declared_root:
        # Intentional session start: minting is permitted and must be tagged.
        return ChainContext(
            trace_id=f"root-{hop_name}",
            parent_span_id="",
            role="root",
        )

    if inbound is None or not inbound.trace_id or not inbound.parent_span_id:
        # Fail closed: do NOT mint a new trace_id for a downstream hop.
        raise TraceParentDivergence(
            f"hop={hop_name} cannot resolve parent: carrier missing or "
            f"parent_span_id empty; refusing to re-root (would sever chain)"
        )

    if inbound.role == "root" and inbound.parent_span_id:
        # A root context should not carry a parent; treat as malformed.
        raise TraceParentDivergence(
            f"hop={hop_name} received root context with non-empty parent "
            f"{inbound.parent_span_id}; parent identity is ambiguous"
        )

    return ChainContext(
        trace_id=inbound.trace_id,          # inherited, never minted
        parent_span_id=inbound.parent_span_id,
        role="downstream",
    )


def validate_connected_trace(spans: list[dict]) -> None:
    """
    Shared trace_id is necessary but not sufficient. Verify the span set
    forms a single connected tree rooted at the session root.
    """
    by_id = {s["span_id"]: s for s in spans}
    roots = [s for s in spans if not s.get("parent_span_id")]
    if len(roots) != 1:
        raise TraceParentDivergence(
            f"trace_forest_detected: {len(roots)} roots under one trace_id; "
            f"correlation over-reports continuity"
        )
    for s in spans:
        pid = s.get("parent_span_id")
        if pid and pid not in by_id:
            raise TraceParentDivergence(
                f"orphan span {s['span_id']}: parent {pid} absent from trace"
            )
