# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-causal-span-link-orphaned-span-reparenting-under-concurrent-trace-export-in-multi-agent-cost-attribution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-causal-span-link-orphaned-span-reparenting-under-concurrent-trace-export-in-multi-agent-cost-attribution.warrant.json
# Markdown SHA-256:   17974f4a9b6b97a540df7dd959d9aa2b55faf52abe220eaf6fa8af1c3d32bead
# Code AST SHA-256:   182d5c8eeea99dda64b3c2fe3940c45b0d21dfd35bd1e8907d603933a58f76e3
# Verified Classes:   TopologyCorruptedTrace, Span, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TopologyCorruptedTrace(RuntimeError):
    """Raised when a trace's cost attribution cannot be trusted because
    a span was reparented across an agent boundary during orphan resolution."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    agent_id: str          # stamped at emission, independent of topology
    cost_basis: float      # tokens * rate, stamped at emission
    resolved: bool = False


@dataclass
class Trace:
    spans: dict = field(default_factory=dict)
    reparented: list = field(default_factory=list)


def attribute_cost(trace: Trace, meters: dict) -> dict:
    """Attribute cost by emission-time agent_id stamp, never by DAG ancestry.
    Reconcile against ground-truth meters; refuse to roll up corrupted traces."""
    per_agent = {}
    for span in trace.spans.values():
        per_agent[span.agent_id] = per_agent.get(span.agent_id, 0.0) + span.cost_basis

    residuals = {}
    for agent_id, meter in meters.items():
        residual = per_agent.get(agent_id, 0.0) - meter
        if abs(residual) > 0.01 * max(meter, 1.0):
            residuals[agent_id] = residual

    if len(residuals) >= 2 and abs(sum(residuals.values())) < 1e-6:
        # Symmetric residuals across roots: signature of a reparented orphan.
        raise TopologyCorruptedTrace(
            f"trace has symmetric cost residuals {residuals}; "
            f"reparented spans: {trace.reparented}. "
            "Exclude from rollups; backfill emission stamps before retry."
        )
    return per_agent


def resolve_orphan(trace: Trace, span: Span, nearest_resolved: Optional[str]) -> None:
    """Reparent an orphaned span. Must record the event so cost reconciliation
    can detect topology corruption downstream."""
    if span.parent_span_id not in trace.spans:
        trace.reparented.append((span.span_id, nearest_resolved))
        if nearest_resolved is None:
            raise TopologyCorruptedTrace(
                f"span {span.span_id} orphaned with no resolved ancestor; "
                "cannot place in trace without synthetic root"
            )
        span.parent_span_id = nearest_resolved
    trace.spans[span.span_id] = span
    span.resolved = True
