# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-opentelemetry-genai-tool-call-span-as-unsealed-before-the-parent-turn-span-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-opentelemetry-genai-tool-call-span-as-unsealed-before-the-parent-turn-span-closes.warrant.json
# Markdown SHA-256:   9e7ce50e60e2882ecd870c6ab4b0920f4a7b268d008afa65e1952293cf3bef87
# Code AST SHA-256:   154c9438199579102b902aa9644a214a5e1b225619c4fe9a9e9d958dd00bbf15
# Verified Classes:   UnsealedToolSpanError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsealedToolSpanError(RuntimeError):
    """Raised when a GenAI tool span is consumed as ground truth before its causal consumer exists."""
    pass


def verify_tool_span_sealed(span: dict, trace_spans: dict) -> None:
    call_id = span.get("gen_ai.tool.call.id")
    if call_id is None:
        raise UnsealedToolSpanError(f"tool span missing gen_ai.tool.call.id: {span.get('name')}")

    sealed_flag = span.get("gen_ai.tool.call.sealed")
    if sealed_flag is None:
        # No explicit seal marker: fall back to causal-consumer presence check.
        consumer_present = any(
            other.get("gen_ai.tool.call.id") == call_id
            and other.get("gen_ai.operation.name") == "chat"
            and other.get("span_id") != span.get("span_id")
            for other in trace_spans.values()
        )
        if not consumer_present:
            raise UnsealedToolSpanError(
                f"tool span {span.get('span_id')} (call.id={call_id}) has no consuming "
                f"model span in trace; refusing to treat as sealed ground truth"
            )
        return

    if sealed_flag is False:
        raise UnsealedToolSpanError(
            f"tool span {span.get('span_id')} (call.id={call_id}) explicitly marked unsealed; "
            f"consumer must wait for turn-span close or seal event"
        )


def reconstruct_chain(trace_spans: dict) -> list:
    ordered = sorted(trace_spans.values(), key=lambda s: s.get("start_time_unix_nano", 0))
    for span in ordered:
        if span.get("gen_ai.operation.name") == "execute_tool":
            verify_tool_span_sealed(span, trace_spans)
    return ordered
