# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-span-attributes-when-a-tool-call-span-is-closed-before-its-deferred-result-arrives.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-span-attributes-when-a-tool-call-span-is-closed-before-its-deferred-result-arrives.warrant.json
# Markdown SHA-256:   724f17d9870429504d7f512e0ff0195f38d9c4de3c158561e73ed1623e6b11e4
# Code AST SHA-256:   7b597747dd268eed7b283e128e586deb3a6dcc82a2e57885a1a109abd51d3a60
# Verified Classes:   UnjoinableToolSpanError, ToolSpanGuard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnjoinableToolSpanError(RuntimeError):
    """Raised when a tool-call span is ended without a result or a call.id-carrying continuation."""
    pass


class ToolSpanGuard:
    def __init__(self, call_id: str):
        self.call_id = call_id
        self.result_attached = False
        self.continuation_registered = False

    def attach_result(self, result) -> None:
        self.result_attached = True

    def register_continuation(self) -> None:
        # The deferred-result span MUST carry gen_ai.tool.call.id = self.call_id
        # and be linked (SpanLink) to the invocation span, not parented to it.
        self.continuation_registered = True

    def end_span(self) -> None:
        if self.result_attached:
            return  # invariant holds: span end is causally after result
        if self.continuation_registered:
            return  # safe: call.id is the join key on the result side
        raise UnjoinableToolSpanError(
            f"tool-call span for call.id={self.call_id} ended with no result "
            f"and no call.id-carrying continuation; trace would assert a "
            f"completed call with no outcome and a separate, unjoinable root span"
        )
