# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-context-propagation-failure-at-an-mcp-to-a2a-handoff-as-a-forensic-data-integrity-fault-rather-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-context-propagation-failure-at-an-mcp-to-a2a-handoff-as-a-forensic-data-integrity-fault-rather-th.warrant.json
# Markdown SHA-256:   07e5b99de3c20369eb39318a4b714303ac12193f3d72828a31e3b202e9d26b63
# Code AST SHA-256:   9e52b7ac21cb6e4dd5917f18408f5d2b6dea2b685967c7e83a9dfd9d4a6a08ea
# Verified Classes:   CorrelationIntegrityFault, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class CorrelationIntegrityFault(RuntimeError):
    """Raised when a trace-replay detects a propagation break that cannot be
    resolved by a non-temporal join key and must be quarantined as evidence."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    service: str
    start_time: float
    end_time: float


def classify_orphan_root(
    orphan: Span,
    candidate_parents: list[Span],
    known_call_edges: set[tuple[str, str]],
    surviving_join_key: Optional[str],
) -> str:
    """Decide whether a rootless sub-tree is a forensic integrity fault, a
    benign logging gap, or a resolvable link.

    Returns one of: 'resolved', 'logging_gap', 'integrity_fault'.
    """
    # Condition 3: a surviving join key downgrades the fault to a gap.
    if surviving_join_key is not None:
        return "resolved"

    # Find a parent span whose window contains the orphan's start and whose
    # service is known to call the orphan's service.
    suspected_boundary = None
    for parent in candidate_parents:
        if parent.trace_id == orphan.trace_id:
            continue
        if not (parent.start_time <= orphan.start_time <= parent.end_time):
            continue
        if (parent.service, orphan.service) not in known_call_edges:
            continue
        suspected_boundary = (parent, orphan)
        break

    # Condition 2: if no boundary is crossed, this is not a propagation break.
    if suspected_boundary is None:
        return "logging_gap"

    # Condition 1 + the no-time-adjacency invariant: a probable break with no
    # surviving join key MUST be quarantined, never auto-merged.
    parent, child = suspected_boundary
    raise CorrelationIntegrityFault(
        f"Correlation break between trace {parent.trace_id} "
        f"(span {parent.span_id}, service={parent.service}) and orphan root "
        f"{child.trace_id} (span {child.span_id}, service={child.service}) "
        f"at boundary {parent.service}->{child.service}. No surviving join key. "
        f"Quarantine both traces; set replay_invalid=true."
    )


def replay_trace(orphan: Span, parents: list[Span], edges: set[tuple[str, str]],
                 join_key: Optional[str]) -> str:
    try:
        return classify_orphan_root(orphan, parents, edges, join_key)
    except CorrelationIntegrityFault as fault:
        # Emit a CorrelationBreak record; do NOT merge by time-adjacency.
        _emit_break_record(orphan, str(fault))
        raise
