# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-spans-when-a-tool-call-child-span-outlives-its-parent-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-spans-when-a-tool-call-child-span-outlives-its-parent-agent-span.warrant.json
# Markdown SHA-256:   d080cfb2969df57c28ec4cbb4606aa039c84dd05bd271ae6f4ebff21be7e2b4f
# Code AST SHA-256:   54ec8191e26b655e6f8c9e2ee02e3a5627243d02a14cc44309577f50d4559898
# Verified Classes:   OrphanedToolSpanError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call span would export without a resolvable parent
    correlation, violating the GenAI containment-or-correlation invariant."""
    pass


def close_agent_span(span, open_tool_children: list[dict]) -> None:
    """Close an invoke_agent span only if every tool child is either closed
    or carries a correlation ID that lets consumers join without nesting."""
    for child in open_tool_children:
        if child["status"] == "open":
            raise OrphanedToolSpanError(
                f"cannot close agent span {span['span_id']}: "
                f"tool span {child['span_id']} still open with no "
                f"completion boundary; defer closure or mark tool_pending"
            )
        if not child.get("gen_ai.tool.call.id"):
            raise OrphanedToolSpanError(
                f"tool span {child['span_id']} lacks gen_ai.tool.call.id; "
                f"late export would be unrecoverable by correlation join"
            )
    span["end_time"] = max(
        [span["end_time"]] + [c["end_time"] for c in open_tool_children]
    )
    span["attributes"]["gen_ai.agent.turn.status"] = "complete"
