# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribution-collapse-when-a-traced-agent-trajectory-is-replayed-across-a-cost-accounting-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribution-collapse-when-a-traced-agent-trajectory-is-replayed-across-a-cost-accounting-boundary.warrant.json
# Markdown SHA-256:   8b6be59783eeab7ba8e87eae24ef9825ca5a648e20c0757399df18976a4f0622
# Code AST SHA-256:   96a30bde0db9c2a01fa22f3f7297add08887ac62d6e85d1b4a5f0a7c83dba40f
# Verified Classes:   SpanAttributionCollapse, Span, CostLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class SpanAttributionCollapse(RuntimeError):
    """Raised when cost/hallucination attribution cannot be joined to the
    trace store by immutable span identity. Indicates a positional join,
    a reused span_id across retries, or a tag written against a span that
    no longer exists in the reconciled trace."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str          # minted once at creation, never reused across retries
    attempt: int          # retry attempt index; new attempt => new span_id
    logical_step: int     # human-facing; NOT a join key
    cost_usd: float = 0.0
    hallucination_tagged: bool = False


@dataclass
class CostLedger:
    rows: Dict[Tuple[str, str], float] = field(default_factory=dict)

    def record(self, span: Span) -> None:
        key = (span.trace_id, span.span_id)
        if key in self.rows:
            # write-once invariant: a span's cost is recorded exactly once
            raise SpanAttributionCollapse(
                f"duplicate cost row for span {key}; span_id reused across retries"
            )
        self.rows[key] = span.cost_usd


def reconcile(trace_spans: Set[Span], ledger: CostLedger) -> Dict[str, float]:
    """Join cost ledger to trace store by (trace_id, span_id) identity.
    Any asymmetry is a hard error — never silently zero."""
    trace_keys = {(s.trace_id, s.span_id) for s in trace_spans}
    ledger_keys = set(ledger.rows.keys())

    missing_in_ledger = trace_keys - ledger_keys
    missing_in_trace = ledger_keys - trace_keys

    if missing_in_ledger:
        raise SpanAttributionCollapse(
            f"spans present in trace but unbilled: {sorted(missing_in_ledger)}"
        )
    if missing_in_trace:
        # classic positional-join symptom: ledger references a span_id that
        # the re-parented trace no longer contains
        raise SpanAttributionCollapse(
            f"ledger references spans absent from reconciled trace: "
            f"{sorted(missing_in_trace)}"
        )

    # hallucination tags must be per-attempt and per-span, never migrated
    tagged = {(s.trace_id, s.span_id) for s in trace_spans if s.hallucination_tagged}
    if not tagged.issubset(trace_keys):
        raise SpanAttributionCollapse("hallucination tag bound to non-existent span")

    return {f"{t}:{s}": ledger.rows[(t, s)] for (t, s) in trace_keys}
