# 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-evidence-rather-than-ground-truth-for-agent-state-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-lossy-evidence-rather-than-ground-truth-for-agent-state-reconstruction.warrant.json
# Markdown SHA-256:   bf534c90e2b5bb0756be281809318dbcaa5b88df947d7be992e5833e49aa1c4b
# Code AST SHA-256:   b792d142aba610e3b01ec1552db9005069c099fb71bf0c25137b1f707efce3a7
# Verified Classes:   LossySpanReconstructionError, SpanRecord, ToolLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Optional


class LossySpanReconstructionError(RuntimeError):
    """Raised when span-derived agent state is too lossy to act on."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    operation: str
    tool_name: Optional[str] = None
    tool_args: Optional[str] = None
    tool_result: Optional[str] = None
    input_tokens: Optional[int] = None   # None = attribute absent
    output_tokens: Optional[int] = None  # None = attribute absent
    end_time_observed: bool = False
    sampled: bool = True


@dataclass
class ToolLedger:
    """Authoritative record of side effects, independent of spans."""
    completed: dict = field(default_factory=dict)  # idempotency_key -> result

    def has_run(self, key: str) -> bool:
        return key in self.completed


def reconstruct_budget(spans: list[SpanRecord], ledger: ToolLedger,
                       token_ceiling: int) -> int:
    """Return confirmed tokens consumed, or raise if reconstruction is unsafe."""
    confirmed = 0
    for s in spans:
        if not s.end_time_observed:
            # span still open at checkpoint: usage not finalized
            raise LossySpanReconstructionError(
                f"span {s.span_id} open at checkpoint; usage attributes not final"
            )
        if s.output_tokens is None:
            # attribute absent — could be sampling, could be zero; indistinguishable
            raise LossySpanReconstructionError(
                f"span {s.span_id} missing output_tokens; cannot treat as zero"
            )
        confirmed += s.output_tokens

    if confirmed > token_ceiling:
        raise LossySpanReconstructionError(
            f"confirmed tokens {confirmed} exceed ceiling {token_ceiling}"
        )
    return confirmed


def decide_tool_call(spans: list[SpanRecord], ledger: ToolLedger,
                     idempotency_key: str, args: str) -> str:
    """Decide whether to issue a side-effecting tool call."""
    # Span stream is corroboration only; ledger is authoritative.
    if ledger.has_run(idempotency_key):
        return ledger.completed[idempotency_key]

    for s in spans:
        if s.tool_name and s.tool_args == args:
            if not s.sampled:
                raise LossySpanReconstructionError(
                    f"span {s.span_id} unsampled; action history incomplete, "
                    "cannot confirm non-execution from span stream"
                )
            if s.tool_result is not None:
                try:
                    json.loads(s.tool_result)
                except json.JSONDecodeError:
                    raise LossySpanReconstructionError(
                        f"span {s.span_id} result truncated or malformed; "
                        "cannot treat as complete"
                    )

    # Not in ledger and no complete span evidence of prior run: issue the call.
    result = f"executed:{idempotency_key}"
    ledger.completed[idempotency_key] = result
    return result
