# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-trace-context-orphaning-when-a-federated-a2a-hop-re-mints-trace-ids-instead-of-propagating-them.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-trace-context-orphaning-when-a-federated-a2a-hop-re-mints-trace-ids-instead-of-propagating-them.warrant.json
# Markdown SHA-256:   1285f2e444a2fb0fa845d6bff5ef1bdbb4149db649a133c763062b08d98ba9ae
# Code AST SHA-256:   ca6a475e470312a79a21f4f0c566567d91c769b2ebe6593342f44c28d0b5338c
# Verified Classes:   TraceOrphanedError, TraceLink, LinkStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceOrphanedError(RuntimeError):
    """Raised when an A2A hop neither propagated nor linked trace context.

    This is non-retryable: retrying re-mints another orphan and worsens
    the causal gap. It must be surfaced as degraded causality, not as a
    transient transport failure.
    """


@dataclass
class TraceLink:
    task_id: str
    parent_trace_id: Optional[str]
    child_trace_id: str
    serving_span_id: str
    boundary_id: str


@dataclass
class LinkStore:
    links: dict = field(default_factory=dict)          # task_id -> [TraceLink]
    known_roots: set = field(default_factory=set)      # child_trace_ids seen

    def record(self, link: TraceLink) -> None:
        # Guard against false-join: a re-minted root must be globally novel.
        if link.child_trace_id in self.known_roots and link.parent_trace_id is None:
            raise TraceOrphanedError(
                f"re-minted trace_id {link.child_trace_id} collides with an "
                f"existing root; refusing to merge unrelated task trees"
            )
        self.links.setdefault(link.task_id, []).append(link)
        self.known_roots.add(link.child_trace_id)


def finish_a2a_hop(
    store: LinkStore,
    task_id: str,
    boundary_id: str,
    propagated_trace_id: Optional[str],
    response: dict,
) -> TraceLink:
    """Postcondition check on an A2A client after a delegated call returns.

    Valid outcomes:
      - callee echoed the propagated trace_id (same trust domain), or
      - callee re-minted and returned a trace_link (cross trust domain).
    Anything else is orphaning and must fail closed.
    """
    returned_trace = response.get("trace_id")
    returned_span = response.get("span_id")

    if returned_trace is None or returned_span is None:
        raise TraceOrphanedError(
            f"task {task_id} across boundary {boundary_id}: callee returned no "
            f"trace identity; causal chain is unrecoverable"
        )

    if propagated_trace_id is not None and returned_trace == propagated_trace_id:
        return TraceLink(task_id, propagated_trace_id, returned_trace,
                         returned_span, boundary_id)

    # Re-minted path: require an explicit link from the callee.
    if response.get("trace_link") is None:
        raise TraceOrphanedError(
            f"task {task_id} across boundary {boundary_id}: trace_id was "
            f"re-minted ({propagated_trace_id!r} -> {returned_trace!r}) with no "
            f"trace_link; refusing to report OK on an unobservable hop"
        )

    link = TraceLink(task_id, propagated_trace_id, returned_trace,
                     returned_span, boundary_id)
    store.record(link)
    return link
