# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-missing-gen-ai-tool-call-id-on-a-resumed-span-as-a-hard-continuity-fault-rather-than-a-cosmetic-attribute-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-missing-gen-ai-tool-call-id-on-a-resumed-span-as-a-hard-continuity-fault-rather-than-a-cosmetic-attribute-gap.warrant.json
# Markdown SHA-256:   dd2557f8544db3181d43ecd76046fcf9093acc94f387311c49d10953b61257b0
# Code AST SHA-256:   778c23cd96a45493962473b7cd994a3ea272cfbcc0656cf72f7d446c1b73b3f1
# Verified Classes:   ContinuityFault, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional, Iterable

SIDE_EFFECTING = {"write_file", "place_order", "send_message", "mutate_record"}


class ContinuityFault(RuntimeError):
    """Raised when a resumed span cannot be safely reconciled or re-executed."""


@dataclass
class Span:
    operation: str
    tool_name: Optional[str]
    tool_call_id: Optional[str]
    conversation_id: str


def validate_resume_window(spans: Iterable[Span], tool_registry: dict) -> None:
    """
    Guardrail: a side-effecting execute_tool span without a dispatch-time
    gen_ai.tool.call.id is a continuity fault, not a cosmetic gap.
    """
    for span in spans:
        if span.operation != "execute_tool":
            continue
        if span.tool_call_id:
            continue  # reconcilable via idempotency ledger

        descriptor = tool_registry.get(span.tool_name or "", {})
        declared_idempotent = descriptor.get("idempotent", False) and not descriptor.get(
            "side_effecting", span.tool_name in SIDE_EFFECTING
        )

        if not declared_idempotent:
            raise ContinuityFault(
                f"execute_tool span for tool={span.tool_name!r} "
                f"conversation={span.conversation_id!r} has no "
                f"gen_ai.tool.call.id and tool is not declared idempotent; "
                f"effect state is unknown — refusing to re-execute, "
                f"route to reconciler."
            )
        # idempotent read-only: re-execution is safe, fall through


def resume_step(spans: list[Span], tool_registry: dict, step_index: int) -> str:
    validate_resume_window(spans, tool_registry)
    target = spans[step_index]
    if target.tool_call_id:
        return f"reconcile:{target.tool_call_id}"
    return "re-execute:safe-readonly"
