# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-stitch-a-parent-trace-across-an-mcp-stdio-sse-transport-re-dial-and-how-does-the-correlation-invariant-br.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-stitch-a-parent-trace-across-an-mcp-stdio-sse-transport-re-dial-and-how-does-the-correlation-invariant-br.warrant.json
# Markdown SHA-256:   f8f79124fd87f22c2f4c61057381ae18d985db82805c93e689cfdcb17aa59777
# Code AST SHA-256:   e79526721ed8feb1c94c8b78b4cdf09611fb189b3c861216eff3e3ca9723c0a2
# Verified Classes:   TraceStitchRefused, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceStitchRefused(RuntimeError):
    """Raised when a parent-child edge would fuse causally distinct transport sessions."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    process_uid: str
    transport_session_id: str
    rpc_id: Optional[int]
    start_time: float
    end_time: float
    is_redial_bridge: bool = False


def stitch_edge(parent: Span, child: Span, live_process_uids: set[str],
                redial_window: tuple[float, float] | None) -> str:
    """Return the resolved parent span_id, or raise TraceStitchRefused."""
    if child.parent_span_id != parent.span_id:
        raise TraceStitchRefused("parent_span_id mismatch; not a candidate edge")

    if child.transport_session_id == parent.transport_session_id:
        return parent.span_id  # same transport session, valid stitch

    # Transport session changed: require an explicit redial bridge.
    if parent.is_redial_bridge:
        return parent.span_id

    parent_dead = parent.process_uid not in live_process_uids
    in_redial = (
        redial_window is not None
        and redial_window[0] <= child.start_time <= redial_window[1]
    )

    if parent_dead and in_redial:
        raise TraceStitchRefused(
            f"refusing stitch: parent {parent.span_id} (proc {parent.process_uid}) "
            f"is dead and child {child.span_id} starts inside redial window; "
            f"emit child as new root tagged orphaned_redial"
        )

    # rpc_id namespace collision across sessions under same trace.
    if (parent.rpc_id is not None
            and child.rpc_id is not None
            and parent.rpc_id == child.rpc_id
            and parent.transport_session_id != child.transport_session_id):
        raise TraceStitchRefused(
            f"rpc_id {child.rpc_id} collides across sessions "
            f"{parent.transport_session_id}->{child.transport_session_id}; "
            f"scope key to (trace_id, session_id, rpc_id)"
        )

    # A start_time clamp would be required to nest child under parent.
    if child.start_time < parent.end_time and child.start_time < parent.start_time:
        raise TraceStitchRefused(
            f"child {child.span_id} start {child.start_time} precedes parent "
            f"start {parent.start_time}; nesting would require time clamp"
        )

    return parent.span_id
