# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-genai-tool-call-span-correlation-has-silently-collapsed-under-opentelemetry-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-genai-tool-call-span-correlation-has-silently-collapsed-under-opentelemetry-semantic-conventions.warrant.json
# Markdown SHA-256:   fc85e1883f52dec8b2ee1d8f00e5ddb6bdab0c3f7abb676e21eaa314973c37bc
# Code AST SHA-256:   65a91972d8ac04c5714374d783b673b66b2ed67958d56fb7b56b19a39852690a
# Verified Classes:   ToolCallCorrelationCollapsed, SpanView
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class ToolCallCorrelationCollapsed(RuntimeError):
    """Raised when GenAI tool-call spans cannot be joined to their requesting model invocations."""


@dataclass(frozen=True)
class SpanView:
    span_id: str
    operation_name: str          # gen_ai.operation.name
    tool_call_id: str | None     # gen_ai.tool.call.id


def assert_tool_call_correlation(spans: list[SpanView]) -> None:
    """
    Enforce the invariant that every execute_tool span's gen_ai.tool.call.id
    appears as a call id emitted by some chat span in the same trace.
    """
    requested_ids: set[str] = {
        s.tool_call_id
        for s in spans
        if s.operation_name == "chat" and s.tool_call_id
    }
    executed_ids: set[str] = {
        s.tool_call_id
        for s in spans
        if s.operation_name == "execute_tool" and s.tool_call_id
    }

    if not executed_ids:
        # No tool executions: nothing to correlate, invariant is vacuously true.
        return

    unjoined = executed_ids - requested_ids
    if unjoined:
        raise ToolCallCorrelationCollapsed(
            "tool-call correlation collapsed: "
            f"{len(unjoined)} execute_tool span(s) carry gen_ai.tool.call.id "
            f"values absent from any chat span's emitted requests. "
            f"Unjoined ids: {sorted(unjoined)}. "
            "Likely cause: call id regenerated at the tool boundary instead of "
            "threaded from the model-emitted request."
        )


def check_trace(spans: list[SpanView]) -> str:
    try:
        assert_tool_call_correlation(spans)
    except ToolCallCorrelationCollapsed as exc:
        return f"FAIL: {exc}"
    return "OK: tool-call spans join cleanly to requesting model invocations"


if __name__ == "__main__":
    healthy = [
        SpanView("s1", "chat", "call-abc"),
        SpanView("s2", "execute_tool", "call-abc"),
    ]
    collapsed = [
        SpanView("s1", "chat", "call-abc"),
        SpanView("s2", "execute_tool", "call-xyz"),  # regenerated at boundary
    ]
    print(check_trace(healthy))
    print(check_trace(collapsed))
