# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-trace-span-merge-aliasing-under-concurrent-tool-fan-out-and-the-causal-parent-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-trace-span-merge-aliasing-under-concurrent-tool-fan-out-and-the-causal-parent-invariant.warrant.json
# Markdown SHA-256:   7ce0ba79f69365a16d92ac79650471df8b90d025588e5a421c6a143f0ef278fa
# Code AST SHA-256:   5ce3682b1daa82fba54dfaf0b581497a5b52885e9105960ad3304265a422570d
# Verified Classes:   TraceCausalityError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TraceCausalityError(RuntimeError):
    """Raised when a trace is schema-valid but causally unfaithful (aliased spans)."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    call_seq: int          # assigned at dispatch, immutable
    tool_call_id: int      # carried in result envelope; must equal call_seq
    start: float
    end: float
    tokens: int


def validate_attribution(spans: list[Span], fanout_parent: str) -> None:
    """Enforce envelope identity + temporal containment before emitting metrics.

    Call this before any cost/latency/hallucination attribution is derived.
    """
    by_id = {s.span_id: s for s in spans}
    children = [s for s in spans if s.parent_id == fanout_parent]
    if len(children) < 2:
        return  # sequential path: aliasing cannot arise

    parent = by_id.get(fanout_parent)
    if parent is None:
        raise TraceCausalityError(f"missing parent span {fanout_parent}")

    for c in children:
        # (1) envelope identity must match dispatch identity
        if c.tool_call_id != c.call_seq:
            raise TraceCausalityError(
                f"span {c.span_id} aliased: envelope tool_call_id={c.tool_call_id} "
                f"!= dispatch call_seq={c.call_seq}; attribution untrustworthy"
            )
        # (2) temporal containment: child must live inside parent's interval
        if c.start < parent.start or c.end > parent.end:
            raise TraceCausalityError(
                f"span {c.span_id} violates containment: "
                f"[{c.start:.3f},{c.end:.3f}] outside parent "
                f"[{parent.start:.3f},{parent.end:.3f}]; suspected aliasing or clock skew"
            )


def attribute_cost(spans: list[Span], fanout_parent: str) -> dict[str, int]:
    validate_attribution(spans, fanout_parent)
    return {s.span_id: s.tokens for s in spans if s.parent_id == fanout_parent}
