# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-tool-call-spans-from-silently-severing-causal-chains-in-eval-in-production-trace-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-tool-call-spans-from-silently-severing-causal-chains-in-eval-in-production-trace-pipelines.warrant.json
# Markdown SHA-256:   c1bafc0fe3f9530ac05d972bd8dbfeee701e594fc110b159daa3ed181021069c
# Code AST SHA-256:   e99c355ad218080e9ed2296f8c2d1baf37bce7b3397492687f8596e9d83c598f
# Verified Classes:   CausalEdgeError, ToolSpan, LLMSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class CausalEdgeError(RuntimeError):
    """Raised when a tool span cannot be causally linked to its LLM parent."""
    pass


@dataclass
class ToolSpan:
    span_id: str
    call_id: str
    structural_parent_id: str
    causal_parent_id: str | None = None
    edge_state: str = "unresolved"  # unresolved | resolved | ambiguous


@dataclass
class LLMSpan:
    span_id: str
    tool_call_ids: list[str] = field(default_factory=list)


def resolve_causal_edge(tool: ToolSpan, llm_spans: list[LLMSpan]) -> ToolSpan:
    """Resolve a tool span's causal parent via call_id correspondence.

    Never falls back to structural_parent_id: that field reflects the
    execution stack (dispatcher/worker), not the reasoning that emitted
    the call, and using it manufactures a plausible-but-wrong edge.
    """
    if not re.fullmatch(r"[A-Za-z0-9_\-]{8,}", tool.call_id):
        raise CausalEdgeError(
            f"tool span {tool.span_id}: call_id {tool.call_id!r} is not a "
            f"trace-unique identifier; per-turn counters violate the invariant"
        )

    matches = [s for s in llm_spans if tool.call_id in s.tool_call_ids]

    if len(matches) == 0:
        # Parent may not have arrived yet (out-of-order collector). Defer.
        tool.edge_state = "unresolved"
        return tool
    if len(matches) > 1:
        # Duplicate call_id within trace: ambiguous, must suppress scoring.
        tool.edge_state = "ambiguous"
        return tool

    tool.causal_parent_id = matches[0].span_id
    tool.edge_state = "resolved"
    return tool


def score_attribution(tool: ToolSpan, llm_spans: list[LLMSpan]) -> float | None:
    """Eval-in-production hook: attribution score, or None if not scorable."""
    resolve_causal_edge(tool, llm_spans)

    if tool.edge_state != "resolved":
        # Fail closed: do not fold into the faithfulness denominator as 0.0.
        return None

    parent = next(s for s in llm_spans if s.span_id == tool.causal_parent_id)
    if not parent.tool_call_ids:
        raise CausalEdgeError(
            f"tool span {tool.span_id}: causal parent {parent.span_id} "
            f"has empty tool_calls[]; edge resolved against a truncated span"
        )
    # ... faithfulness scoring against parent completion omitted ...
    return 1.0
