# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-identity-when-a-planner-span-retries-and-the-executor-span-s-parent-id-is-re-bound-mid-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-identity-when-a-planner-span-retries-and-the-executor-span-s-parent-id-is-re-bound-mid-trace.warrant.json
# Markdown SHA-256:   7173178ecf30549a9b2fd886b0008432f117eaf51dcff15dd16b389d2f279e86
# Code AST SHA-256:   cb958aa6f6cef3c045c88d354a3464b4a9eb170d4b8bae407af43cfa2e5ba02c
# Verified Classes:   CausalTraceCorruption, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalTraceCorruption(RuntimeError):
    """Raised when a span's declared parent attempt does not match the
    attempt whose output the span actually consumed."""
    pass


@dataclass
class Span:
    span_id: str
    logical_step_id: str
    attempt_id: int
    parent_span_id: Optional[str]
    consumed_from_attempt: Optional[int] = None  # attempt whose output fed this span
    causal_predecessor: Optional[str] = None     # set only for commit-partial edges


def stitch(spans: list[Span]) -> dict[str, Span]:
    """Assemble a span set into a causal index, rejecting attempt-inconsistent
    parenting. Returns span_id -> Span on success."""
    by_id = {s.span_id: s for s in spans}
    index: dict[str, Span] = {}

    for s in spans:
        if s.parent_span_id is None:
            index[s.span_id] = s
            continue

        parent = by_id.get(s.parent_span_id)
        if parent is None:
            raise CausalTraceCorruption(
                f"span {s.span_id} names missing parent {s.parent_span_id}"
            )

        # Invariant: a child consumed output from the attempt it declares as
        # parent, OR it carries an explicit causal_predecessor edge recording
        # the cross-attempt dependency (commit-partial resolution).
        consumed = s.consumed_from_attempt
        if consumed is not None and consumed != parent.attempt_id:
            if s.causal_predecessor is None:
                raise CausalTraceCorruption(
                    f"span {s.span_id} consumed attempt {consumed} but is "
                    f"parented to attempt {parent.attempt_id} of "
                    f"{parent.logical_step_id} with no causal_predecessor edge; "
                    f"trace would mis-attribute work to the wrong planner attempt"
                )
            # commit-partial: predecessor must exist and belong to the consumed attempt
            pred = by_id.get(s.causal_predecessor)
            if pred is None or pred.attempt_id != consumed:
                raise CausalTraceCorruption(
                    f"span {s.span_id} causal_predecessor {s.causal_predecessor} "
                    f"does not belong to consumed attempt {consumed}"
                )

        # Attempt-consistent parenting for same-step children.
        if parent.logical_step_id == s.logical_step_id and parent.attempt_id != s.attempt_id:
            if s.causal_predecessor is None:
                raise CausalTraceCorruption(
                    f"span {s.span_id} attempt {s.attempt_id} parented under "
                    f"attempt {parent.attempt_id} of the same logical step "
                    f"{s.logical_step_id} without a causal_predecessor edge"
                )

        index[s.span_id] = s

    return index
