# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-attribute-span-level-cost-when-a-federated-agent-hop-rewrites-trace-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-attribute-span-level-cost-when-a-federated-agent-hop-rewrites-trace-identity.warrant.json
# Markdown SHA-256:   c498eeed54490061c1e197ba22f094c3cb02fdaf89c076826aa06776d4d613f9
# Code AST SHA-256:   2bfcad54d445f3a57fdc2a8bddddea10bc02f613f344dace8dc72b67b468202a
# Verified Classes:   TraceIdentityDiscontinuity, SpanContext, SpanLink, OutboundSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceIdentityDiscontinuity(RuntimeError):
    """Raised when a federated hop breaks causal attribution without a resolvable link."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    sampled: bool


@dataclass(frozen=True)
class SpanLink:
    trace_id: str
    span_id: str


@dataclass(frozen=True)
class OutboundSpan:
    context: SpanContext
    links: tuple[SpanLink, ...]
    local_cost_usd: float
    local_duration_ms: float


def assert_attributable(
    inbound: SpanContext,
    outbound: OutboundSpan,
    *,
    tolerance_usd: float = 0.0,
) -> None:
    """
    Assert the causal-attribution invariant at a federated hop boundary.

    Valid iff the outbound span preserves the inbound trace identity, or it
    carries a link back to the inbound span. Sampling must not be dropped
    when the inbound span was sampled in.
    """
    preserves_identity = outbound.context.trace_id == inbound.trace_id
    has_resolvable_link = any(
        link.trace_id == inbound.trace_id and link.span_id == inbound.span_id
        for link in outbound.links
    )

    if not (preserves_identity or has_resolvable_link):
        raise TraceIdentityDiscontinuity(
            f"hop rewrote trace identity: inbound {inbound.trace_id}/{inbound.span_id} "
            f"-> outbound {outbound.context.trace_id}/{outbound.context.span_id} "
            f"with no link back to the causal ancestor"
        )

    if inbound.sampled and not outbound.context.sampled:
        raise TraceIdentityDiscontinuity(
            f"hop dropped sampling on {inbound.trace_id}: parent sampled in, "
            f"child trace {outbound.context.trace_id} sampled out; "
            f"cost would be attributed to an unobserved trace"
        )

    if outbound.local_cost_usd < -tolerance_usd:
        raise TraceIdentityDiscontinuity(
            f"negative local cost {outbound.local_cost_usd} on span "
            f"{outbound.context.span_id}; ledger reconciliation will undercount"
        )
