# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-a-causal-trace-when-a-multi-hop-tool-chain-replays-non-deterministically-and-the-reconstructor-s-span-joins-silently-for.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-a-causal-trace-when-a-multi-hop-tool-chain-replays-non-deterministically-and-the-reconstructor-s-span-joins-silently-for.warrant.json
# Markdown SHA-256:   31d96483116aa2cc7f985a02a50530a9115100abdc1ce760536fd9b7c7413e07
# Code AST SHA-256:   dfe4ced1ce2411131d72efcb548741ffa21bc6bcc5c6fff7b998cdca56e48b30
# Verified Classes:   ForkedJoinError, UnverifiedCausalEdgeError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ForkedJoinError(RuntimeError):
    """Raised when a causal join key resolves to more than one successor span.

    A fork means the reconstructor cannot assert a unique causal edge; any
    downstream verdict (regression, cost, blame) would be corrupted by picking
    a child by timestamp or arrival order.
    """


class UnverifiedCausalEdgeError(RuntimeError):
    """Raised when an edge crosses a causal_opaque tool and no token binds it."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    replay_epoch: str
    parent_span_id: Optional[str]
    hop_index: int
    tool: str
    output_fingerprint: str
    causal_token: Optional[str] = None
    nondeterministic: bool = False
    causal_opaque: bool = False
    start_time: float = 0.0


def join_key(span: Span) -> tuple:
    # Epoch is part of the key: replay spans cannot collide with originals.
    return (span.trace_id, span.replay_epoch, span.parent_span_id, span.hop_index)


def reconstruct_chain(spans: list[Span], trace_id: str, epoch: str) -> list[Span]:
    """Reconstruct a single causal chain, failing closed on any fork.

    Invariant: for each join key, exactly one successor. We refuse to fall back
    to first-by-start-time, because that silently pairs spans from different
    executions when a fork exists.
    """
    by_key: dict[tuple, list[Span]] = {}
    for s in spans:
        if s.trace_id != trace_id or s.replay_epoch != epoch:
            continue
        by_key.setdefault(join_key(s), []).append(s)

    # Root: parent is None at hop 0.
    root_candidates = by_key.get((trace_id, epoch, None, 0), [])
    if len(root_candidates) != 1:
        raise ForkedJoinError(
            f"root join for trace={trace_id} epoch={epoch} resolved to "
            f"{len(root_candidates)} spans; expected exactly 1"
        )

    chain = [root_candidates[0]]
    current = root_candidates[0]
    while True:
        key = (trace_id, epoch, current.span_id, current.hop_index + 1)
        candidates = by_key.get(key, [])
        if not candidates:
            break
        if len(candidates) > 1:
            ids = [c.span_id for c in candidates]
            raise ForkedJoinError(
                f"forked join at parent={current.span_id} hop={current.hop_index + 1}: "
                f"candidates={ids}. Refusing to resolve by start_time."
            )
        child = candidates[0]
        # Causal binding: child must carry the parent's token, or the parent
        # must be non-opaque and the child must reference the parent's output.
        if current.causal_opaque and child.causal_token != current.causal_token:
            raise UnverifiedCausalEdgeError(
                f"edge {current.span_id}->{child.span_id} crosses causal_opaque "
                f"tool {current.tool} without a matching token"
            )
        chain.append(child)
        current = child
    return chain


def assert_epoch_isolated(spans: list[Span]) -> None:
    """Guard: no span may share (trace_id, parent, hop) across epochs without
    the epoch being in the join key. This is the precondition that makes
    reconstruct_chain sound."""
    seen: dict[tuple, Span] = {}
    for s in spans:
        k = (s.trace_id, s.parent_span_id, s.hop_index)
        if k in seen and seen[k].replay_epoch != s.replay_epoch:
            raise ForkedJoinError(
                f"epoch collision: {seen[k].span_id} (epoch={seen[k].replay_epoch}) "
                f"and {s.span_id} (epoch={s.replay_epoch}) share join key {k}"
            )
        seen[k] = s
