# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-an-agent-span-when-opentelemetry-genai-tool-call-attributes-are-still-unresolved.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-an-agent-span-when-opentelemetry-genai-tool-call-attributes-are-still-unresolved.warrant.json
# Markdown SHA-256:   218795dd5075b358b4572746cf48c58bd17b287c965d5b213dc295905a68c8a3
# Code AST SHA-256:   cefc474d29e781cd94fd622c82c758e9388a6010cdd44f866c9fe3499adf7be0
# Verified Classes:   UnresolvedSpanError, ToolCallState, AgentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnresolvedSpanError(RuntimeError):
    """Raised when a span is closed while a named tool call is still in flight."""
    pass


@dataclass
class ToolCallState:
    call_id: str
    attempt: int = 1
    resolved: bool = False
    outcome: Optional[str] = None


@dataclass
class AgentSpan:
    operation: str
    attributes: dict = field(default_factory=dict)
    pending_tool_calls: dict = field(default_factory=dict)
    closed: bool = False
    unresolved_marker: Optional[str] = None


def close_span(span: AgentSpan, deadline_s: float, start_ts: float) -> None:
    """Close an agent span only when all named tool calls are resolved,
    or the bounded deadline has elapsed (in which case mark unresolved)."""
    if span.closed:
        raise UnresolvedSpanError(f"span {span.operation} already closed")

    in_flight = [c for c in span.pending_tool_calls.values() if not c.resolved]
    elapsed = time.monotonic() - start_ts

    if in_flight and elapsed < deadline_s:
        # Contract violation: caller tried to finalize before resolution
        # and before the deadline. Refuse rather than emit a false record.
        raise UnresolvedSpanError(
            f"cannot close span {span.operation}: "
            f"{len(in_flight)} tool call(s) unresolved "
            f"({[c.call_id for c in in_flight]}) and deadline not reached"
        )

    if in_flight:
        # Deadline elapsed: close with an explicit unresolved marker so
        # downstream cost reconciliation can distinguish unknown from zero.
        span.unresolved_marker = "tool_result_unresolved"
        span.attributes["error.type"] = "tool_result_unresolved"

    span.closed = True


def run_agent_step(span: AgentSpan, tool_latency_s: float, deadline_s: float) -> None:
    start = time.monotonic()
    # simulate async tool still pending at the moment the runtime wants to end
    span.pending_tool_calls["call-7"] = ToolCallState(call_id="call-7")
    # runtime attempts to finalize immediately (the buggy pattern):
    close_span(span, deadline_s=deadline_s, start_ts=start)
