# 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-non-authoritative-for-tool-call-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-tool-call-reconstruction.warrant.json
# Markdown SHA-256:   1a26a59d65cd8f05ff0edb2216efd26b121f5ddf6778782fe0b86f2d1928db48
# Code AST SHA-256:   f7d6ed58528aae8d42a126b0397f3a02b3eb1894e051f17da12b6a06c584553f
# Verified Classes:   LossyTelemetryError, ToolSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class LossyTelemetryError(RuntimeError):
    """Raised when span attributes cannot faithfully reconstruct a tool call."""
    pass


@dataclass
class ToolSpan:
    call_id: str
    tool_name: str
    arguments_json: str          # as emitted to the collector
    recorded_arg_len: int        # authoritative length from runtime
    redacted: bool
    sampled_out: bool


SIDE_EFFECT_PREFIXES = ("send_", "write_", "delete_", "transfer_", "post_")


def reconstruct_tool_call(span: ToolSpan, checkpoint_store: dict) -> dict:
    # 1. Sampling gap: the call never reached the collector intact.
    if span.sampled_out:
        raise LossyTelemetryError(
            f"tool call {span.call_id} was sampled out; spans are not authoritative"
        )

    # 2. Redaction drift: arguments were scrubbed in-flight.
    if span.redacted:
        raise LossyTelemetryError(
            f"tool call {span.call_id} arguments were redacted; cannot replay"
        )

    # 3. Truncation: emitted length diverges from recorded length.
    if len(span.arguments_json) != span.recorded_arg_len:
        raise LossyTelemetryError(
            f"tool call {span.call_id} arguments truncated "
            f"({len(span.arguments_json)} != {span.recorded_arg_len})"
        )

    # 4. Non-idempotent tools require the authoritative checkpoint, always.
    if span.tool_name.startswith(SIDE_EFFECT_PREFIXES):
        ckpt = checkpoint_store.get(span.call_id)
        if ckpt is None:
            raise LossyTelemetryError(
                f"no authoritative checkpoint for side-effecting call {span.call_id}; "
                f"refusing to reconstruct from telemetry"
            )
        return ckpt

    # 5. Only here is the span projection safe to use.
    return {"call_id": span.call_id, "args": json.loads(span.arguments_json)}
