# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-trace-continuity-when-a2a-task-graph-edges-are-stitched-from-span-timestamps-instead-of-propagated-causal-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-trace-continuity-when-a2a-task-graph-edges-are-stitched-from-span-timestamps-instead-of-propagated-causal-tokens.warrant.json
# Markdown SHA-256:   13f449800be3cf15ee8b1517265acbc887e61a2f58b9d0130ca5b67de1244597
# Code AST SHA-256:   e80813c01f4e0416eb6afb8498ee72d6e811307131b8df9cbe8385917c866e3a
# Verified Classes:   CausalStitchError, Span, StitchResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalStitchError(RuntimeError):
    """Raised when a federated collector cannot soundly join spans across an A2A edge."""


@dataclass
class Span:
    span_id: str
    task_id: str
    attempt_id: Optional[str]
    causal_parent_token: Optional[str]
    agent: str
    start_ts: float
    end_ts: float
    terminal: bool = True


@dataclass
class StitchResult:
    edges: list = field(default_factory=list)
    forks: list = field(default_factory=list)
    gaps: list = field(default_factory=list)


def stitch(spans: list[Span], allow_timestamp_fallback: bool = False) -> StitchResult:
    """
    Join spans into a causal graph. Refuses to guess edges it cannot prove
    unless the caller explicitly opts into the (unsound) timestamp fallback.
    """
    result = StitchResult()
    by_task: dict[str, list[Span]] = {}
    for s in spans:
        by_task.setdefault(s.task_id, []).append(s)

    for task_id, group in by_task.items():
        # Group by attempt: attempts are the true causal children of a dispatch.
        attempts: dict[Optional[str], list[Span]] = {}
        for s in group:
            attempts.setdefault(s.attempt_id, []).append(s)

        # Sound path: every attempt carries an immutable causal token.
        if all(s.causal_parent_token for s in group) and all(a is not None for a in attempts):
            for s in group:
                result.edges.append((s.causal_parent_token, s.span_id))
            if len(attempts) > 1:
                result.forks.append({"task_id": task_id, "attempts": list(attempts)})
            continue

        # Unsound path: multiple attempt-roots with no causal token.
        if len(attempts) > 1 or None in attempts:
            if not allow_timestamp_fallback:
                raise CausalStitchError(
                    f"ambiguous causal edge for task {task_id!r}: "
                    f"{len(attempts)} attempt-root(s), missing causal token. "
                    f"Refusing to stitch by timestamp; emit as causal gap."
                )
            # Explicit opt-in fallback: still must not merge sibling attempts.
            ordered = sorted(group, key=lambda s: s.start_ts)
            for prev, nxt in zip(ordered, ordered[1:]):
                if nxt.start_ts < prev.end_ts and prev.attempt_id != nxt.attempt_id:
                    result.gaps.append(
                        {"task_id": task_id, "reason": "overlapping_sibling_attempts",
                         "attempts": [prev.attempt_id, nxt.attempt_id]}
                    )
            continue

        # Single attempt, no token: safe only if strictly serialized.
        if not all(s.terminal for s in group):
            raise CausalStitchError(
                f"task {task_id!r} has non-terminal span without causal token; "
                f"cannot prove serialization precondition."
            )
        result.gaps.append({"task_id": task_id, "reason": "no_causal_token_single_attempt"})

    return result


def replay_verify(spans: list[Span], expected_root: str) -> bool:
    """Verifier replay: must be a pure function of recorded spans."""
    res = stitch(spans, allow_timestamp_fallback=False)
    roots = {p for p, _ in res.edges if p is not None}
    if res.forks:
        raise CausalStitchError(
            f"replay hit forked task graph {res.forks!r}; "
            f"verifier must reconcile per-attempt, not per-task."
        )
    if expected_root not in roots and res.edges:
        raise CausalStitchError(
            f"replay root {expected_root!r} absent from stitched graph; "
            f"recorded state is causally incomplete."
        )
    return True
