# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-turn-span-when-tool-call-child-spans-report-gen-ai-tool-call-id-values-that-do-not-re.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-turn-span-when-tool-call-child-spans-report-gen-ai-tool-call-id-values-that-do-not-re.warrant.json
# Markdown SHA-256:   2473064497b26671b88910b49bd949930679ebf2c9900a7c3a05133c6990271d
# Code AST SHA-256:   26c2415e57eb219593936a6cf4bb894fd3585d34558d782e83f79777d3896fcc
# Verified Classes:   ToolCallReconciliationError, TurnSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class ToolCallReconciliationError(RuntimeError):
    """Raised when a GenAI agent-turn span cannot be closed coherently."""
    pass

@dataclass
class TurnSpan:
    turn_id: str
    declared_tool_call_ids: set[str]
    observed_tool_call_ids: set[str] = field(default_factory=set)
    events: list[dict] = field(default_factory=list)
    closed: bool = False

def close_agent_turn_span(
    span: TurnSpan,
    *,
    strict: bool = True,
) -> None:
    """
    Enforce the reconciliation invariant before closing a GenAI agent-turn span.

    - observed subset of declared, no missing -> OK
    - observed subset of declared, missing   -> annotate 'unexecuted', OK
    - observed NOT subset of declared        -> hard error (orphan tool calls)
    """
    if span.closed:
        raise ToolCallReconciliationError(
            f"turn {span.turn_id}: span already closed; double-close detected"
        )

    declared = set(span.declared_tool_call_ids)
    observed = set(span.observed_tool_call_ids)

    orphans = observed - declared
    if orphans:
        # A tool executed that the turn never declared: id collision or
        # cross-context mis-parenting. Never close OK.
        raise ToolCallReconciliationError(
            f"turn {span.turn_id}: orphan tool-call ids not declared by parent: "
            f"{sorted(orphans)}; declared={sorted(declared)} observed={sorted(observed)}"
        )

    missing = declared - observed
    if missing:
        # Legitimate divergence (dedup / budget cancel / router short-circuit).
        # Must be recorded, not silently dropped.
        for call_id in sorted(missing):
            span.events.append(
                {
                    "name": "gen_ai.tool.call.unexecuted",
                    "attributes": {
                        "gen_ai.tool.call.id": call_id,
                        "gen_ai.tool.call.status": "unexecuted",
                        "reason": "deduplicated|budget_cancelled|router_short_circuit",
                    },
                }
            )
        if strict and not span.events:
            raise ToolCallReconciliationError(
                f"turn {span.turn_id}: missing children but no annotation emitted"
            )

    span.closed = True
