# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-token-attribution-record-it-cannot-reconcile-across-a-federated-swarm-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-token-attribution-record-it-cannot-reconcile-across-a-federated-swarm-boundary.warrant.json
# Markdown SHA-256:   6ba70d4910c7a6ad2bf10327b6a69239713d6de4da966137ec0207927e1e3a25
# Code AST SHA-256:   c08deb76f4489498ab6ce942eb63faeffead86e764a34054af74146e6a197453
# Verified Classes:   UnreconcilableAttributionError, SpanIdentity, AttributionRecord, CausalRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreconcilableAttributionError(RuntimeError):
    """Raised when a token-attribution record cannot be uniquely resolved
    to a causal origin within the federated swarm. The caller must emit a
    gap record instead of a best-effort attribution."""
    pass


@dataclass
class SpanIdentity:
    tenant: str
    span_id: str
    nonce: str


@dataclass
class AttributionRecord:
    span: SpanIdentity
    parent: Optional[SpanIdentity]
    prompt_tokens: int
    completion_tokens: int
    derived_from: list = field(default_factory=list)  # list[SpanIdentity]
    is_root: bool = False


class CausalRegistry:
    def __init__(self):
        self._committed = {}       # (tenant, span_id) -> SpanIdentity
        self._superseded = set()   # nonces that a retry replaced

    def commit(self, ident: SpanIdentity):
        self._committed[(ident.tenant, ident.span_id)] = ident

    def supersede(self, ident: SpanIdentity):
        self._superseded.add((ident.tenant, ident.span_id, ident.nonce))

    def resolve(self, ident: SpanIdentity) -> Optional[SpanIdentity]:
        return self._committed.get((ident.tenant, ident.span_id))

    def is_superseded(self, ident: SpanIdentity) -> bool:
        return (ident.tenant, ident.span_id, ident.nonce) in self._superseded


def reconcile_or_gap(rec: AttributionRecord, reg: CausalRegistry) -> dict:
    # Root spans must not carry a parent; non-roots must resolve uniquely.
    if rec.is_root:
        if rec.parent is not None:
            raise UnreconcilableAttributionError(
                f"root span {rec.span.span_id} carries a parent; lineage ambiguous"
            )
        return {"status": "attributed", "origin": rec.span.span_id,
                "tokens": rec.prompt_tokens + rec.completion_tokens}

    if rec.parent is None:
        raise UnreconcilableAttributionError(
            f"non-root span {rec.span.span_id} has no parent; cannot attribute"
        )

    resolved = reg.resolve(rec.parent)
    if resolved is None:
        raise UnreconcilableAttributionError(
            f"parent {rec.parent.span_id} of {rec.span.span_id} does not resolve "
            f"in registry (orphan from dropped/retried header)"
        )

    if reg.is_superseded(rec.parent):
        raise UnreconcilableAttributionError(
            f"parent {rec.parent.span_id} nonce {rec.parent.nonce} superseded by "
            f"retry; lineage ambiguous between two parents"
        )

    # Non-root prompt tokens must declare derived_from coverage, else
    # re-counted context is indistinguishable from fresh tokens.
    if rec.prompt_tokens > 0 and not rec.derived_from:
        raise UnreconcilableAttributionError(
            f"span {rec.span.span_id} has {rec.prompt_tokens} prompt tokens but no "
            f"derived_from tags; re-counted context cannot be subtracted"
        )

    for d in rec.derived_from:
        if reg.resolve(d) is None:
            raise UnreconcilableAttributionError(
                f"derived_from {d.span_id} of {rec.span.span_id} unresolved"
            )

    return {"status": "attributed", "origin": resolved.span_id,
            "tokens": rec.completion_tokens,
            "derived_tokens": rec.prompt_tokens}


def emit_with_gate(rec: AttributionRecord, reg: CausalRegistry) -> dict:
    try:
        return reconcile_or_gap(rec, reg)
    except UnreconcilableAttributionError as exc:
        # Downgrade to explicit gap; never fabricate a parent.
        return {
            "status": "gap",
            "span_id": rec.span.span_id,
            "raw_tokens": rec.prompt_tokens + rec.completion_tokens,
            "reason": str(exc),
        }
