# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-emission-with-tool-call-side-effects-when-a-tool-invocation-succeeds-but-its-span-is-dropped.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-emission-with-tool-call-side-effects-when-a-tool-invocation-succeeds-but-its-span-is-dropped.warrant.json
# Markdown SHA-256:   5fa73e55b18190b729206f58cbb965630c1713e75603075cb54281aaee0d43be
# Code AST SHA-256:   2af432eef5c94843291a42c0eade2082e48ec1e8841fc71b699527a186a873d7
# Verified Classes:   ToolMutability, TelemetryCommitError, ToolCallIntent, DurableToolExecutor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ToolMutability(Enum):
    READ_ONLY = "read_only"
    MUTATING = "mutating"


class TelemetryCommitError(RuntimeError):
    """Raised when a mutating tool's side effect committed but its durable
    gen_ai.tool.call record could not be persisted. The planner MUST treat
    this as a tool failure and follow an idempotent recovery path."""
    pass


@dataclass
class ToolCallIntent:
    call_id: str
    tool_name: str
    mutability: ToolMutability
    idempotent: bool


class DurableToolExecutor:
    def __init__(self, intent_store, span_exporter, tool_registry):
        self.intent_store = intent_store      # transactional, fsync'd
        self.span_exporter = span_exporter    # may be lossy batch
        self.tool_registry = tool_registry

    def execute(self, call_id: str, tool_name: str, args: dict) -> dict:
        spec = self.tool_registry[tool_name]
        intent = ToolCallIntent(
            call_id=call_id,
            tool_name=tool_name,
            mutability=spec.mutability,
            idempotent=spec.idempotent,
        )

        # Phase 1: write-ahead intent for mutating tools, BEFORE side effect.
        if intent.mutability is ToolMutability.MUTATING:
            self.intent_store.write_intent(intent)  # must fsync

        # Phase 2: execute. Side effect may commit here.
        result = spec.invoke(**args)

        # Phase 3: for mutating tools, the durable completion record is the
        # authority. Span is emitted best-effort; its loss is backfillable.
        if intent.mutability is ToolMutability.MUTATING:
            committed = self.intent_store.write_complete(intent, result)
            if not committed:
                # Side effect committed but we cannot prove it durably.
                # Surface as failure so planner uses idempotent recovery.
                if not intent.idempotent:
                    raise TelemetryCommitError(
                        f"side effect for {tool_name} (call_id={call_id}) committed "
                        f"but durable record failed; tool is non-idempotent, "
                        f"manual reconciliation required"
                    )
                raise TelemetryCommitError(
                    f"side effect for {tool_name} (call_id={call_id}) committed "
                    f"but durable record failed; re-invoke is safe (idempotent)"
                )

        # Span emission is best-effort for all tools; the intent store is the
        # audit authority for mutating ones.
        self.span_exporter.emit_tool_call_span(intent, result)
        return result


def reconcile_backfill(intent_store, trace_backend) -> int:
    """Emit synthetic backfill spans for committed side effects whose
    original gen_ai.tool.call span was dropped by the batch exporter."""
    backfilled = 0
    for complete in intent_store.iter_complete():
        if not trace_backend.has_span(complete.call_id):
            trace_backend.emit_backfill_span(
                call_id=complete.call_id,
                tool_name=complete.tool_name,
                attributes={"gen_ai.tool.call.backfilled": True},
            )
            backfilled += 1
    return backfilled
