# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-agent-span-misattribution-when-parallel-tool-call-fan-out-exceeds-the-parent-span-s-emit-window.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-agent-span-misattribution-when-parallel-tool-call-fan-out-exceeds-the-parent-span-s-emit-window.warrant.json
# Markdown SHA-256:   88e08f4efebd8a3c8e220fb415b735e88336395edf9e57043321b06799371938
# Code AST SHA-256:   f507da26b43a63fe9be544a253236d43b8ddf63bf6069c457535e14526c7389a
# Verified Classes:   SpanEmitWindowViolation, AgentSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Set


class SpanEmitWindowViolation(RuntimeError):
    """Raised when an agent span finalizes usage/end_time before all
    spawned tool-call children have been acknowledged as exported."""


@dataclass
class AgentSpan:
    span_id: str
    trace_id: str
    spawned_tool_call_ids: Set[str] = field(default_factory=set)
    acked_tool_call_ids: Set[str] = field(default_factory=set)
    usage_finalized: bool = False
    end_time: float | None = None

    def spawn_tool_call(self, tool_call_id: str) -> None:
        if self.usage_finalized or self.end_time is not None:
            raise SpanEmitWindowViolation(
                f"cannot spawn tool call {tool_call_id!r} on already-closed "
                f"agent span {self.span_id!r}"
            )
        self.spawned_tool_call_ids.add(tool_call_id)

    def ack_tool_call_export(self, tool_call_id: str) -> None:
        if tool_call_id not in self.spawned_tool_call_ids:
            raise SpanEmitWindowViolation(
                f"ack for unspawned tool call {tool_call_id!r} on span "
                f"{self.span_id!r}"
            )
        self.acked_tool_call_ids.add(tool_call_id)

    def finalize(self, end_time: float, output_tokens: int) -> None:
        pending = self.spawned_tool_call_ids - self.acked_tool_call_ids
        if pending:
            # The invariant: no usage finalization while any child is unacked.
            raise SpanEmitWindowViolation(
                f"agent span {self.span_id!r} cannot finalize usage "
                f"({output_tokens} tokens) at t={end_time}: "
                f"{len(pending)} tool-call child(ren) unacked: {sorted(pending)}"
            )
        self.usage_finalized = True
        self.end_time = end_time


def close_agent_turn(
    span: AgentSpan,
    soft_deadline: float,
    actual_export_times: Dict[str, float],
    output_tokens: int,
) -> float:
    """Close the agent turn honoring deferred finalization.

    The orchestrator's soft deadline is demoted to a *backgrounding* signal:
    it may stop awaiting, but it may not close the span. The span closes at
    max(child ack time), never earlier than the last spawned child's export.
    """
    for tool_call_id, export_time in actual_export_times.items():
        span.ack_tool_call_export(tool_call_id)

    if soft_deadline < max(actual_export_times.values(), default=soft_deadline):
        # Soft deadline was exceeded; we do NOT close early. We only record
        # that the deadline was breached and let finalization use the true
        # max-child ack time.
        pass

    true_end = max(actual_export_times.values(), default=soft_deadline)
    span.finalize(end_time=true_end, output_tokens=output_tokens)
    return true_end
