# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-causal-trace-graph-when-a-retrieval-span-s-parent-pointer-is-rewritten-by-a-retrying-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-causal-trace-graph-when-a-retrieval-span-s-parent-pointer-is-rewritten-by-a-retrying-tool-call.warrant.json
# Markdown SHA-256:   0a48741ad133239619113ea7bc77e1c6b5c75649621f78074a4e5fae1f8454dc
# Code AST SHA-256:   b2a6db8e8e5a1a778772d7c33ba3cb3f153c4206a1227239e0a178469eca4a2e
# Verified Classes:   CausalAttributionError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalAttributionError(RuntimeError):
    """Raised when a span's causal parent claim contradicts temporal evidence."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    start: float
    end: float
    kind: str  # "prompt" | "tool" | "retrieval" | "synthesis"


def attach_to_parent(child: Span, parent: Span, allow_override: bool = False) -> None:
    if child.parent_id != parent.span_id:
        raise CausalAttributionError(
            f"span {child.span_id} declares parent {child.parent_id}, "
            f"not {parent.span_id}; refusing to rewrite claim"
        )
    # Temporal containment is the evidence; the parent pointer is only a claim.
    if not (child.start >= parent.start and child.end <= parent.end):
        if not allow_override:
            raise CausalAttributionError(
                f"span {child.span_id} [{child.start},{child.end}] not contained "
                f"in parent {parent.span_id} [{parent.start},{parent.end}]; "
                f"likely retry-rewritten parent pointer — quarantine for reconciliation"
            )
        # Override requires an explicit, provenance-stamped link, never silent repair.
        child.kind = child.kind + "+override"


def reconcile_retry(retrieval: Span, attempt1: Span, attempt2: Span) -> Span:
    # Retrieval outlives the failed attempt it points at: reattach to the live retry.
    if retrieval.parent_id == attempt1.span_id and retrieval.end > attempt1.end:
        retrieval.parent_id = attempt2.span_id
        attach_to_parent(retrieval, attempt2)
        return retrieval
    raise CausalAttributionError(
        f"retrieval {retrieval.span_id} could not be reconciled to a live attempt"
    )
