# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-a-divergent-tool-call-ledger-before-emitting-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-a-divergent-tool-call-ledger-before-emitting-lineage.warrant.json
# Markdown SHA-256:   51a32071649a61879f60333ca55afc755ccbe3cc97cd21384f94da903d960475
# Code AST SHA-256:   ff8a84643d853bd47d3db26bf5a35cfc6b2b5fa891b9198f8f6ce25a17bd4a02
# Verified Classes:   LineageReconciliationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class LineageReconciliationError(RuntimeError):
    """Raised when OTel GenAI spans cannot be reconciled to the execution ledger
    before token accounting or lineage emission."""
    pass


def reconcile_invocation(invocation_id, tool_spans, ledger_attempts, token_budget):
    # tool_spans: list of dicts with gen_ai.tool.call.id, gen_ai.usage.*
    # ledger_attempts: dict attempt_id -> {logical_call_id, committed: bool}
    logical_tokens = {}
    quarantined = []

    for span in tool_spans:
        attempt_id = span["gen_ai.tool.call.id"]
        entry = ledger_attempts.get(attempt_id)
        if entry is None:
            # Span exists with no ledger commitment: partial, orphaned, or
            # retry-discarded. Must not be summed into logical totals.
            quarantined.append(attempt_id)
            continue
        logical = entry["logical_call_id"]
        if entry["committed"]:
            logical_tokens[logical] = logical_tokens.get(logical, 0) + span.get(
                "gen_ai.usage.input_tokens", 0
            ) + span.get("gen_ai.usage.output_tokens", 0)

    # Invariant: every non-quarantined span maps to a committed logical call,
    # and no logical call has uncommitted attempts pending reconciliation.
    pending = [
        a for a, e in ledger_attempts.items()
        if not e["committed"] and a not in quarantined
    ]
    if pending:
        raise LineageReconciliationError(
            f"invocation {invocation_id}: {len(pending)} attempts uncommitted "
            f"and unreconciled; lineage emission blocked"
        )

    total = sum(logical_tokens.values())
    if total > token_budget:
        raise LineageReconciliationError(
            f"invocation {invocation_id}: reconciled logical token total {total} "
            f"exceeds budget {token_budget}; refusing to emit lineage over "
            f"overcounted telemetry"
        )

    return {
        "invocation_id": invocation_id,
        "logical_call_count": len(logical_tokens),
        "logical_tokens": logical_tokens,
        "quarantined_attempts": quarantined,
    }
