# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-correlation-across-a2a-hops-when-the-downstream-agent-rewrites-its-own-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-correlation-across-a2a-hops-when-the-downstream-agent-rewrites-its-own-trace-context.warrant.json
# Markdown SHA-256:   f3e2c8c173702a3e4cc873f1bfe440176c4ef9e48dd44c51e91189468ca643c8
# Code AST SHA-256:   dac00c212a9c2e10c120b69d9b06e317da4ef7344c19e75171e6786368808c7f
# Verified Classes:   TraceCorrelationError, SpanRef
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceCorrelationError(RuntimeError):
    """Raised when an A2A hop cannot be reconciled into the parent trace."""


@dataclass
class SpanRef:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    links: tuple[tuple[str, str], ...] = ()


def reconcile_hop(parent: SpanRef, child: SpanRef, declared_mode: str) -> str:
    """
    Enforce the correlation invariant for one A2A edge.

    Returns the effective join key the collector must use for this hop.
    Raises TraceCorrelationError when the hop is unobservable under its
    declared mode.
    """
    if declared_mode == "strict":
        if child.trace_id != parent.trace_id:
            raise TraceCorrelationError(
                f"strict hop forked trace: parent={parent.trace_id} "
                f"child={child.trace_id}"
            )
        if child.parent_span_id != parent.span_id:
            raise TraceCorrelationError(
                f"strict hop broken parent link: expected {parent.span_id} "
                f"got {child.parent_span_id}"
            )
        return child.trace_id

    if declared_mode == "linked":
        expected = (parent.trace_id, parent.span_id)
        if expected not in child.links:
            raise TraceCorrelationError(
                f"linked hop missing link to {expected}; "
                f"child links={child.links!r}"
            )
        return f"link:{parent.trace_id}:{parent.span_id}"

    if declared_mode == "uncorrelated":
        return f"gap:{parent.trace_id}"

    raise TraceCorrelationError(f"unknown correlation_mode={declared_mode!r}")


def reconstruct_request(spans: list[SpanRef], modes: list[str]) -> dict:
    """
    Walk a request's hop chain and return per-hop join keys, or raise if any
    hop violates its declared correlation mode.
    """
    if len(spans) < 2 or len(modes) != len(spans) - 1:
        raise TraceCorrelationError(
            f"malformed chain: {len(spans)} spans, {len(modes)} modes"
        )
    joins = [spans[0].trace_id]
    for i, mode in enumerate(modes):
        joins.append(reconcile_hop(spans[i], spans[i + 1], mode))
    if len(set(joins)) != 1 and "strict" in modes:
        raise TraceCorrelationError(
            f"strict chain produced multiple join keys: {joins!r}"
        )
    return {"root": spans[0].trace_id, "joins": joins, "modes": modes}
