# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-cost-attribution-from-raw-token-events-because-otel-genai-span-attributes-are-lossy-across-a-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-cost-attribution-from-raw-token-events-because-otel-genai-span-attributes-are-lossy-across-a-retry-boundary.warrant.json
# Markdown SHA-256:   075b37cc158eaa8f103d7685950cd8840698d37da8d1d6cae00eb3665cee7db4
# Code AST SHA-256:   d9700d66eafa351f78e82524d0a6992bc5033a0adba5089650b40d8083efc59b
# Verified Classes:   CostAttributionDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CostAttributionDivergence(RuntimeError):
    """Raised when OTel GenAI span-derived cost cannot be reconciled to billed usage."""
    pass


def attribute_cost_from_spans(step_id: str, attempt_spans: list[dict],
                              billed_tokens: int) -> dict:
    """
    Re-derive logical-step cost from ALL attempt spans (including ERROR spans
    that consumed tokens), keyed by a stable agent.step.id, priced per attempt's
    own gen_ai.system. Refuses to emit a number if the derivation cannot be
    reconciled to billed usage.
    """
    if not attempt_spans:
        raise CostAttributionDivergence(
            f"step {step_id}: no attempt spans found; cannot attribute cost"
        )

    derived = 0
    providers = set()
    for span in attempt_spans:
        if span.get("agent.step.id") != step_id:
            raise CostAttributionDivergence(
                f"step {step_id}: span {span.get('span_id')} carries mismatched "
                f"agent.step.id={span.get('agent.step.id')!r}; retry context detached"
            )
        # ERROR spans that reached inference still consumed tokens; include them.
        consumed = (span.get("gen_ai.usage.input_tokens", 0)
                    + span.get("gen_ai.usage.output_tokens", 0))
        if span.get("otel.status_code") == "ERROR" and consumed == 0:
            # Genuinely zero-consumption failure (e.g., connection refused): skip.
            continue
        derived += consumed
        providers.add(span.get("gen_ai.system"))

    if len(providers) > 1 and not all(
        s.get("provider.billed_on_receipt") is not None for s in attempt_spans
    ):
        raise CostAttributionDivergence(
            f"step {step_id}: multi-provider failover without billed_on_receipt "
            f"flag; per-provider pricing cannot be applied"
        )

    if derived != billed_tokens:
        raise CostAttributionDivergence(
            f"step {step_id}: derived {derived} tokens from {len(attempt_spans)} "
            f"attempt span(s) but provider billed {billed_tokens}; "
            f"span attributes are lossy across the retry boundary"
        )

    return {"step_id": step_id, "tokens": derived, "providers": sorted(providers)}
