# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-stitching-from-silently-re-parenting-tool-spans-after-an-agent-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-stitching-from-silently-re-parenting-tool-spans-after-an-agent-retry.warrant.json
# Markdown SHA-256:   fd7ceff66d2fd2cfa74d5f8d469e6fcac1ce8e1189f93ca4dfa17a028d3b13fc
# Code AST SHA-256:   c4b88d5bffcd047d3ef3d7de04da818d2f82dc37d9c50073429b9021e8a0d803
# Verified Classes:   CausalStitchError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class CausalStitchError(RuntimeError):
    """Raised when a child span cannot be causally stitched to a parent attempt."""

@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    step_id: str
    attempt_seq: int          # attempt-scoped discriminator
    parent_request_id: Optional[str]
    start_ns: int
    kind: str                 # "agent_step" | "llm" | "tool"

def stitch_tool_span(tool: Span, candidate_parents: list[Span]) -> Span:
    """
    Stitch a tool span to exactly one parent attempt.
    Invariant: unique attempt-scoped discriminator match AND parent attempt epoch
    strictly precedes child start. Reject ambiguity; never fall back to arrival order.
    """
    if tool.kind != "tool":
        raise CausalStitchError(f"expected tool span, got {tool.kind!r}")

    # 1. Filter to parents whose attempt discriminator matches the child's.
    matches = [
        p for p in candidate_parents
        if p.trace_id == tool.trace_id
        and p.step_id == tool.step_id
        and p.attempt_seq == tool.attempt_seq
        and (tool.parent_request_id is None or p.parent_request_id == tool.parent_request_id)
    ]

    # 2. Ambiguity is fatal, not resolvable by arrival order.
    if len(matches) > 1:
        raise CausalStitchError(
            f"ambiguous causal parent for tool span {tool.span_id} "
            f"(step={tool.step_id}, attempt={tool.attempt_seq}, "
            f"candidates={[p.span_id for p in matches]})"
        )
    if not matches:
        raise CausalStitchError(
            f"no causal parent for tool span {tool.span_id} "
            f"(step={tool.step_id}, attempt={tool.attempt_seq}); "
            f"quarantine, do not attach to nearest step_id match"
        )

    parent = matches[0]

    # 3. Attempt epoch must strictly precede child start.
    if parent.start_ns >= tool.start_ns:
        raise CausalStitchError(
            f"causal ordering violated: parent {parent.span_id} "
            f"(t={parent.start_ns}) not before child {tool.span_id} (t={tool.start_ns})"
        )

    return Span(
        trace_id=tool.trace_id,
        span_id=tool.span_id,
        parent_span_id=parent.span_id,
        step_id=tool.step_id,
        attempt_seq=tool.attempt_seq,
        parent_request_id=tool.parent_request_id,
        start_ns=tool.start_ns,
        kind=tool.kind,
    )
