# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-causal-lineage-attribution-in-multi-agent-traces-when-a-handoff-spans-asynchronous-tool-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-causal-lineage-attribution-in-multi-agent-traces-when-a-handoff-spans-asynchronous-tool-re-entry.warrant.json
# Markdown SHA-256:   1019b902cc53732509b9596f2762c92c0cf6c064055d7b0e2bbb003545e5c71b
# Code AST SHA-256:   74973ea4dc81dd65b775e7673682fb166a4ef2e5a9dac4b500ce610afd89618b
# Verified Classes:   LineageAttributionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LineageAttributionError(RuntimeError):
    """Raised when a lineage edge cannot be attributed to a causal parent."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    instance: str
    transport_parent: Optional[str] = None
    origin_context_id: Optional[str] = None
    dedup_attributed_to: list = field(default_factory=list)


def attribute_edge(parent: Span, child: Span) -> str:
    """
    Return 'attributable' or 'contested' for the edge parent -> child.
    Raises LineageAttributionError only when the caller demands a definitive
    causal attribution and the evidence is insufficient.
    """
    if child.origin_context_id is None or parent.origin_context_id is None:
        # Unverifiable carrier continuity: never silently trust.
        return "contested"

    carrier_continuous = (
        parent.origin_context_id == child.origin_context_id
    )
    third_party_triggered = (
        len(child.dedup_attributed_to) > 0
        and parent.instance not in child.dedup_attributed_to
    )

    if carrier_continuous and not third_party_triggered:
        return "attributable"
    return "contested"


def require_causal_parent(parent: Span, child: Span) -> None:
    """
    Strict mode: used by blame/cost rollups that refuse to charge a span
    to an instance without verified causal parentage.
    """
    verdict = attribute_edge(parent, child)
    if verdict != "attributable":
        raise LineageAttributionError(
            f"edge {parent.span_id}->{child.span_id} is contested: "
            f"transport_parent={child.transport_parent}, "
            f"parent.origin_context_id={parent.origin_context_id}, "
            f"child.origin_context_id={child.origin_context_id}, "
            f"dedup_attributed_to={child.dedup_attributed_to}"
        )
