# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-lossy-projections-rather-than-authoritative-state-for-token-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-lossy-projections-rather-than-authoritative-state-for-token-accounting.warrant.json
# Markdown SHA-256:   e73606b4d5ea764c1d7941469466a873e7d2baa716d7c70ff787cd32a1fb148f
# Code AST SHA-256:   5a513953b0431c16ed5852302639e1e35245ed1cf1e759f3d97d3934eff30ab4
# Verified Classes:   TelemetryProjectionError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TelemetryProjectionError(RuntimeError):
    """Raised when a control decision would be derived from a lossy GenAI span projection."""
    pass


def enforce_budget_from_spans(
    spans: list[dict],
    hard_ceiling_tokens: int,
    sampling_ratio: float,
    ledger_tokens_spent: int,
) -> int:
    """
    Attempt to derive remaining budget from gen_ai.usage.* span attributes.

    Refuses when the span stream is not a valid state source: sampled below 1.0,
    or diverging from the synchronous ledger beyond tolerance. Returns remaining
    budget ONLY when the projection is provably complete.
    """
    if sampling_ratio < 1.0:
        raise TelemetryProjectionError(
            f"Span stream sampled at {sampling_ratio:.2f}; summed gen_ai.usage.* "
            f"undercounts spend by ~{1/sampling_ratio:.1f}x. Refusing to gate budget "
            f"on a lossy projection. Use the synchronous ledger."
        )

    span_sum = sum(
        s.get("gen_ai.usage.input_tokens", 0) + s.get("gen_ai.usage.output_tokens", 0)
        for s in spans
        if s.get("gen_ai.operation.name") == "chat"
    )

    tolerance = max(16, int(0.02 * ledger_tokens_spent))
    if abs(span_sum - ledger_tokens_spent) > tolerance:
        raise TelemetryProjectionError(
            f"Span usage ({span_sum}) diverges from ledger ({ledger_tokens_spent}) "
            f"beyond tolerance {tolerance}; retry/duplicate spans or dropped spans "
            f"present. Trace is evidence, not state — reconcile before enforcing."
        )

    remaining = hard_ceiling_tokens - ledger_tokens_spent
    return max(0, remaining)


def reconstruct_tool_call(spans: list[dict], call_id: str, ledger: dict) -> dict:
    """
    Rebuild a tool call for resume. Spans supply the join key and ordering only;
    arguments and terminal status MUST come from the ledger.
    """
    matching = [s for s in spans if s.get("gen_ai.tool.call.id") == call_id]
    if not matching:
        raise TelemetryProjectionError(
            f"No execute_tool span for call_id={call_id}; cannot confirm whether the "
            f"side effect committed. Treat as unknown, do not re-issue blindly."
        )

    span = matching[-1]
    entry = ledger.get(call_id)
    if entry is None:
        raise TelemetryProjectionError(
            f"Span for call_id={call_id} exists but no ledger entry: arguments and "
            f"terminal status are not standardized span attributes. Refusing to "
            f"reconstruct from projection alone."
        )

    if entry.get("status") not in ("ok", "error"):
        raise TelemetryProjectionError(
            f"call_id={call_id} has no terminal status (in-flight or crashed mid-call). "
            f"Reconcile with the tool before any retry to avoid duplicate side effects."
        )

    return {
        "call_id": call_id,
        "tool": span.get("gen_ai.tool.name"),
        "arguments": entry["arguments"],
        "status": entry["status"],
        "result": entry.get("result"),
    }
